vue 上传文件

Vue上传文件,不必使用什么element 的uplaod, 也不用什么npm上找的个人写的包,就用原生的Vue加axios就行了, 废话不多说,直接上代码:
html:

<input type="file" value="" id="file" @change="uploadConfig">

注意这里的type是file,就表示是上传文件了

js:

      uploadConfig(e) {
        let formData = new FormData();
        formData.append('file', e.target.files[0]);
        let url = this.$store.state.path + "api/tools/handle_upload_file";
        let config = {
          headers:{'Content-Type':'multipart/form-data'}
        };
        this.$axios.post(url,formData, config).then(function (response) {
          console.log(response.data)

        })

      }

1. vue里面的axios,如果要用这种方式写,注意请求方式是method, 而不是 type:

this.$axios({
          url:this.$store.state.path + "api/tools/handle_upload_file",
          method: "POST",    //  这个地方注意
          data: formData,
          file:e.target.files[0],
          processData:false,
          contentType:false,
          success:(response) => {
            console.log("upload_success_response:", response)
        }
        })

2. 传输文件类型,必须加上请求头:   headers:{'Content-Type':'multipart/form-data'}
3. 注意axios的用法

后端(python):

def handle_upload_file(request):
    if request.method == "POST":

        file = request.FILES.get("file")    # 获取文件要用request.FILES
        print file

        for chunk in file.chunks():      # 分块读取二进制文件的方法
            print chunk

    return HttpResponse(json.dumps({"meta": 200, "msg": "ok"}))

猜你喜欢

转载自www.cnblogs.com/zhang-can/p/9116159.html