el-upload文件上传问题

el-upload 文件上传组件使用问题

<el-upload />

问题一:上传成功后,BE返回上传结果文件(文件流格式数据)

使用Blob数据类型对文件流格式类型数据进行转换。

解决思路:替换el-upload的上传请求,在请求中设置 responseType: 'blob' ,将返回的数据类型改为blob
(默认返回的类型是json,即 responseType: 'json')

上传方法

主要还是将el-upload组件获取到的文件数据截取出来,并放到表单类型数据中

uploadRequest(param) {
      // eslint-disable-next-line prefer-const
      let sendFile = new FormData();	// 设置表单数据类型
      sendFile.append('file', param.file);	// 将el-upload组件获取到的文件信息赋值给表单数据
      axios({
        method: 'post',
        url: '/api/fba-address/upload',
        data: sendFile,
        responseType: 'blob',	// 设置返回数据的类型为blob
      }).then((response) => {
          ...

文件流数据处理方法

saveFile(data, fileName) {
    const blob = new Blob([data.data], { type: 'application/vnd.ms-excel' });	// 实例化blob对象,并设置blob导出的文件类型(excel)
    const url = window.URL || window.webkitURL;	// 创建链接地址对象,用于创建下载链接
    const fileURL = url.createObjectURL(blob);	// 创建下载链接
    const a = document.createElement('a');	// 创建DOM元素,a标签
    a.href = fileURL;		// 设置a标签的链接地址
    a.download = fileName;	// 设置文件名,由方法形参传入
    a.target = '_self';		// 设置a标签的打开方式
    a.click();		// 触发a标签的点击事件
    url.revokeObjectURL(fileURL);	// 销毁地址
}

问题二:上传前的操作,before-upload返回false无效

在使用 http-request 自定义上传事件后,before-uploadreturn false 拦截就失效了

解决思路:将 return false 替换成 return Promise ,即返回 reject(false)

beforeUploadFN(file) {
    return Promise((resolve, reject) => {
        // 此处加入判断条件,判断拦截的上传事件
		if (file.type.split('/')[1] !== 'pdf') {
			...
			return reject(false)
		} else {
            return resolve(true)
        }
    })
}
原文地址:https://www.cnblogs.com/CreateBox/p/15205724.html