Vue使用input(type=file)上传文件

<a-icon type="plus-square" @click="uploadMaterial()" />  
<input type="file" style="display:none" ref="file" @click="e => {e.target.value = '';} " @change="getFileData"
/>

触发方法

@click="e => {e.target.value = ‘’;} " 设置这个方法是为了防止上传两次相同的文件,会触发不了

 uploadMaterial() {
      this.$refs.file.dispatchEvent(new MouseEvent("click"));
    },
    // 触发上传材料文件
    getFileData() {
      const inputFile = this.$refs.file.files[0];
      let filename = inputFile.name;
      // 此处应向后台请求 后台保存上传文件名称返回fileId作为文件标识
      let param = {
         fileId: data.fileId,
         file: inputFile
      };
      this.uploadFile(param);
    },
    // 最后上传
    uploadFile(param) {
      let formData = new FormData();
      formData.set("fileName", param.fileId);
      formData.set("file", param.file);
      upload({
        formData
      }).then(() => {
        this.$message.success("上传成功");
      });
    },
export function upload(param) {
  return request({
    url: "xxxxxx",
    method: "post",
    data: param,
    headers: { "Content-Type": "multipart/form-data" },
    transformRequest: function(data) {
      const formData = new FormData();
      let i = data.formData.entries();
      let j = i.next();
      while (!j.done) {
        formData.set(j.value[0], j.value[1]);
        j = i.next();
      }
      return formData;
    }
  });
}
import axios from "axios";
/**
 * 封装axios异步请求的方法==================
 */
//创建一个axios对象-----------
const request = axios.create({
  //baseURL:'/dev-api',//基础路径
  baseURL: process.env.VUE_APP_BASE_API, //根据不同的环境,加载不同的常量值
  //  baseURL: '/',
  timeout: 50000 //请求超时,50000毫秒
});
//设置请求拦截器====================================
//对拦截进行请求--------------------
request.interceptors.request.use(
  config => {
    //请求拦截
    config.data = {
      ...config.data
    };
    return config;
  },
  error => {
    //出现异常
    return Promise.reject(error); //es6写法
  }
);
//设置响应拦截器==================================
//对拦截进行响应--------------------
request.interceptors.response.use(
  response => {
    if (!response.data || response.data == "") {
      return '{"flag":"failure","msg":"未知错误"}';
    }
    return response.data;
  },
  error => {
    return Promise.reject(error);
  }
);
export default request; //导出自定义创建的axios对象,供其他组件进行使用

``

你可能感兴趣的:(Vue,前端)