vue2+axios上传文件

513 阅读1分钟

一、背景

开发过程中需要根据特定的条件下,使用到input标签来上传文件,并且需要上传多个参数的情况下

二、html代码

可以先让元素隐藏然后通过 this.$refs来获取到元素

  <div>
    <input
      type="file"
      ref="file"
      accept=".xls,.xlsx"
      @change="handleFileChange"
      style="display: none"
    />
    <button type="primary" @click="scoresRecording">上传文件</button>
  </div>

三、Methods部分

  methods: {
    // 点击上传文件
    scoresRecording() {
      // 判断是否符合条件触发上传
      // return
      this.$refs.file.click();
    },

    // file上传文件
    async handleFileChange(e) {
      const file = e.target.files[0];
      // 可以通过file.type来判断是否自己想要文文件类型
      const formdata = new FormData();
      formdata.append("file", file); // file是文件
      formdata.append("batchId", "123123"); // batchId是需要的其他key
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer token",
        },
      };
      const res = await importParamsInfo(formdata, config);
      console.log("res =====>", res);
    },
  },

四、接口部分

import axios from 'axios'

export function importParamsInfo(params, config) {
    return axios
        .post(
            `https://XXX`,
            params,
            config
        )
}

五、需要注意的点

axios默认格式请求是 'Content-Type: application/json' 就是json格式

  • 可以设成:
  • 普通表单形式'Content-Type: application/x-www-form-urlencoded'
  • 上传文件格式 'Content-Type: multipart/form-data'

六、实现的功能

994cf834031ba875d3551b9bdb50a13.png

0f5152cc8afc9c52c955f9f06439102.png