Bootstrap

vue中上传文件之multipart/form-data

首先在项目里用了拦截器的,由于拦截器会将传递的参数转成对象,所以你i提交的时候会发现multipart/form-data或转变成application/json

其次关于input的文件上传是需要一个非常纯净的axios的,于是我就在main.js里重新挂载了一个axios

//main.js
//自定义
var instance = axios.create({
  baseURL:'',
  timeout:5000,
  headers:{"Content-Type":"multipart/form-data"}
});
 
Vue.prototype.axios = axios;
Vue.prototype.instance=instance;

在组件中上传代码

var img_file = this.$refs.inputs;
            var formData = new FormData(img_file);
            var fileObj = img_file.files[0];
            console.log(formData)
            formData.append("dsc","dsc");
            formData.append("file",fileObj);
            console.log(fileObj)
            this.instance.post(url,formData).then((res)=>{
                    this.getInit()
            })

就这样就可以正常上传文件

在这里顺便也记一下下载后端返回的文件资源

axios.get(url, {
                responseType: 'blob', //重要
            }).then(response => {
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                let fname = 'report.pdf';
                link.href = url;
                link.setAttribute('download', fname);
                document.body.appendChild(link);
                link.click();
            })

url为后台返回的资源地址,这里会报跨域的错,找后台设置一下就好了

注:测试的时候发现在火狐浏览器上会报错 Argument 1 of FormData.constructor does not implement interface HTMLFormEle

自需要做如下更改就好

//var img_file = this.$refs.inputs;
            //var evt=window.event || el;
            //console.log(evt)
            var img_file = evt.target.files[0];
            console.log(img_file) 
            var formData = new FormData(document.getElementById('uploadForm')[0]);
            //var fileObj = img_file.files[0];
            var fileObj = img_file
            console.log(formData)
            formData.append("dsc","dsc");
            formData.append("file",fileObj);
            console.log(fileObj)
            this.instance.post(url,formData).then((res)=>{
                    this.getInit()
            })

 

转载于:https://www.cnblogs.com/ldlx-mars/p/10647091.html

;