1 <el-upload 2 class="avatar-uploader" 3 action 4 name="file1" 5 :show-file-list="false" 6 :http-request="uploadImg"
7 >
8 <div class="upload-btn">上傳</div>
9 </el-upload>
:http-request="uploadImg" 為重寫的上傳方法
uploadImg(fileObj) { let formData = new FormData(); formData.set("file", fileObj.file); axios .post('接口地址', formData, { headers: { "Content-type": "multipart/form-data" } }).then().catch();
首先創建一個空的文件對象,let formData = new FormData();
然后通過 set 方法,把獲取到的圖片/文件,裝入文件對象中;
然后設置請求頭;
1 //POST傳參序列化 2 axios.interceptors.request.use( 3 config => { 4 console.log(config, "request"); 5 if (config.method === "post") { 6 let curPost = config.url.split("/")[config.url.split("/").length - 1]; 7 if (curPost === "uploadpicture" || curPost === "uploadfile") { 8 return config; // 這里對上傳文件/圖片的 api 不做傳參序列化處理 9 } else { 10 config.data = qs.stringify(config.data); 11 return config; 12 } 13 } 14 return config; 15 }, 16 error => { 17 return Promise.reject(error); 18 } 19 );
最重要的一步:
傳參不能序列化,否則傳遞的就不是文件(file),導致上傳無法成功。