• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LDLX@Y火星
博客园    首页    新随笔    联系   管理    订阅  订阅

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()
            })

 

posted @ 2019-04-03 10:14  火星黑洞  阅读(7846)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3