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();
     let data = JSON.stringify({
        user: "username",
        env: "dev"
      })
        formData.append('file', e.target.files[0]);
     formData.append('data', data); // 上傳文件的同時, 也可以上傳其他數據 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
     data = request.POST.get("data") # 從POST請求中獲取其他數據, 提前在formData中定義的
print file for chunk in file.chunks():      # 分塊讀取二進制文件的方法 print chunk return HttpResponse(json.dumps({"meta": 200, "msg": "ok"}))

 

 

 

 

關於下載文件, 本質就是創建一個a標簽,把文件放在a標簽中, 也可以直接把下載按鈕寫成a標簽, 直接跳轉到服務器的下載接口, 不過這樣會跳轉頁面

看一個demo

 1 download(){
 2   let self = this;
 3   let url = self.$store.state.path + "tools/download_file";
 4   let data = JSON.stringify({
 5     user: self.$store.state.username,
 6     file_name: self.plist_file_name
 7   });
 8   console.log("data:", data)
 9   self.$axios(
10     {
11       method: "post",
12       url: url,
13       data: data,
14       responseType: "blob",    // 指定獲取數據的類型為blob
15     }
16   ).then(
17     function (response) {
18       data = response.data;
      // 創建a標簽並點擊, 即觸發下載
19       let url = window.URL.createObjectURL(new Blob([data]));
20       let link = document.createElement("a");
21       link.style.display = "none";
22       link.href = url;
23       link.setAttribute("download", self.plist_file_name);
24 
25       document.body.appendChild(link);
26       link.click()
27     }
28   ).catch(function (err) {
29     console.log(err)
30   })
31 
32 
33 }

 

python端代碼(Django):

def download_file(request):
    if request.method == "POST":
        data = json.loads(request.body)
        response = {}
        file_name = data.get("file_name")
        if not file_name:
            response["meta"] = {"code": 400}
            response["error"] = {"error_msg": "parameter error, no file_path"}
            return HttpResponse(json.dumps(response))
        file_path = "/tmp/file/" + file_name
        file = open(file_path, "rb")
        response = HttpResponse(file)
        response["Content-Type"] = "application/octet-stream"
        response["Content-Disposition"] = "attachment;filename={}".format(file_name)
        return response

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM