zoukankan      html  css  js  c++  java
  • 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()
                })
  • 相关阅读:
    Codeforces Gym 100571A A. Cursed Query 离线
    codeforces Gym 100500 J. Bye Bye Russia
    codeforces Gym 100500H H. ICPC Quest 水题
    codeforces Gym 100500H A. Potion of Immortality 简单DP
    Codeforces Gym 100500F Problem F. Door Lock 二分
    codeforces Gym 100500C D.Hall of Fame 排序
    spring data jpa 创建方法名进行简单查询
    Spring集成JPA提示Not an managed type
    hibernate配置文件中的catalog属性
    SonarLint插件的安装与使用
  • 原文地址:https://www.cnblogs.com/ldlx-mars/p/10647091.html
Copyright © 2011-2022 走看看