el-upload new FormData上传文件

912 阅读1分钟

el-upload可以自定义上传方式,这种方法很少用,一般都是直接action直接上传,但是实际工作还是会有要求加密之类的,自己封装好的axios有加密,上传再封装一个是没有必要的,所以可以使用new FromData这种方式去上传

action=""设置为空,:http-request自定义方法上传文件

<el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="handleAvatarSuccess.bind(null, { data: item, index: index })"></el-upload>

踩坑点:这里是需要添加headers将其转换为二进制文件,没有这样就只会得到一个uid的对象,提交给后端的是不完整的一个对象

//api.ts
export function upload(file: any) {
  return request({
    url: '/file/upload',
    method: 'post',
    data: file,
    //关键,这里是将其转换为二进制文件,没有这样就只会得到一个uid的对象
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
}

new FormData是一个file的二进制通过post请求传过去给后端

const handleAvatarSuccess = (obj, res) => {
  const formData = new FormData();
  // 添加文件对象
  formData.append('file', res.file);
  console.log('object', formData, res.file);
  upload(formData).then(response => {
    console.log('response', response)
  });
};