ajax文件流下载、文件流导入(上传)

本文详细介绍了使用Axios进行文件流下载和上传的方法,包括如何设置responseType参数以适应不同类型的响应数据,以及如何处理blob和arraybuffer响应类型。同时,还探讨了如何从响应头获取文件名,并提供了非IE和IE10以上的下载解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

都使用的axios插件

注意: responseType是axios的参数,不是在请求头里设置。之前在拦截器中加在请求头里,下载的文件乱码了

文件流下载

1、post方法

axios({
	method: 'post',
	url: 'http://127.0.0.1/detail/list/export?mealcomeTime=1558691428000&rand=9848',
	responseType: 'blob',
	data: data,
	headers: {
		sessionId: 'c22824d846c94a459bf60cf286349399',
		sign: 'a29b3e56399e58d91459be2e64a8dbf9ecbfcd8097af08fb38ede3c64b15a889',
	}
}).then(response => {
//var  disposition = res.headers['content-disposition']
let fileName = window.decodeURI(response.headers['content-disposition'].split('=')[1]);
let link = document.createElement("a");
link.href = window.URL.createObjectURL(new Blob([response.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"}));
link.target = "_blank";
link.download = fileName;
document.body.appendChild(link); 
link.click();
document.body.removeChild(link);
				})
//另外一种  .then后的处理结果
   if (res.success == false) {
       this.$message.error(res.message)
     } else {
       const content = res
       const blob = new Blob([content])
       const fileName = 'XXXX.xlsx'
       if ('download' in document.createElement('a')) {
          // 非IE下载
         const elink = document.createElement('a')
         elink.download = fileName
         elink.style.display = 'none'
         elink.href = URL.createObjectURL(blob)
         document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
                  document.body.removeChild(elink)
                } else {
                  // IE10+下载
                  navigator.msSaveBlob(blob, fileName)
                }
              }

想用文件名,content-disposition

拿不到文件名?
需要后台响应头设置

"Access-Control-Expose-Headers":  "Content-Disposition"

意思让浏览器能访问这个响应头的Content-Disposition属性内容

2、get方法

就是把methods换了一下

export function downFile(url,parameter){
  return axios({
    url: url,
    params: parameter,
    method:'get' ,
    responseType: 'blob'
  })
}
 downFile('xxxxxxxxxxxxxxxx', ExportXls).then((res) => {
          if (res.success == false) {
            this.$message.error(res.message)
          } else {
            const content = res
            const blob = new Blob([content])
            const fileName = 'xxxxxxx.xlsx'
            if ('download' in document.createElement('a')) {
              // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else {
              // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
          }
        })

在网上看到responseType设置为’arraybuffer’

在这里插入图片描述
我们不需要根据服务器返回的情况去随机设置responseType

一、我们要明白,我们在请求下载文件的api时候,可能给我们的返回值有两种情况

	1、直接给我们了我们想要的文件流
	2、还有可能得到了JSON返回数据,让我们展现提示出信息或者被叫为错误信息

二、理解responseType
axios中这样描述的:responseType`表示服务器响应的数据类型,可以是 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’, ‘stream’

不过我经常用blob,其实用什么都无所谓,主要看在拿到返回值的时候如何处理。

根据response.type返回内容的MIME TYPE 来判断是要下载文件,还是要去做一些JSON数据提示什么的操作。如果是JSON类型那就把Blob通过readAsText转为JSON格式。这种方式通过测试IE10和IE10以上版本。

所以有需要时候把arraybuffer转成Json对象这样设置就可以了,网上栗子。

function getExel(url, params, index) {+
  return new Promise(function(resolve, reject) {
    let data = {
      method: "GET",
      url:url,
      headers: {
        'token':  gettoken("token")
      },
      responseType: 'arraybuffer'
    }
    resolve(axios(data));
  })
注意:responseType应设置为:'arraybuffer'

分割线


this.$Api.getExel("/goodsCheckService/v1/planMaterial/export?idList="+idArray)
          .then(response => {
              let a = document.createElement('a');
              let blob = new Blob([response.data], {type: "application/vnd.ms-excel"}); 
              let objectUrl = URL.createObjectURL(blob);
              a.setAttribute("href",objectUrl);
              a.setAttribute("download", '计划单电子表格.xls');
              a.click();
});

文件流导入(上传)

上传文件需要将请求头的Content-Type设置为multipart/form-data

let file = e.target.files[0];           
 let data = new FormData(); //创建form对象
data.append('file',file);//通过append向form对象添加数据
data.append('chunk','0');

axios.post(
	"http://localhost:8081/api/peixun/vedio/uploadVideo",
	data,
	{ headers: { "Content-Type": "multipart/form-data" } }
).then(function (data) {
	console.log(data);
}, function (err) {
	console.log("err------: ");
	console.log(err);
})

这是我用vue的axios的antd of vue弄的轮子,已经忘记怎么写的了,单文件上传

 //导入
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload(file) {
      this.fileList = [file]
      return false
    },
    handleUpload() {
      const { fileList } = this
      const formData = new FormData()
      fileList.forEach((file) => {
        formData.append('files[]', file)
      })
      this.uploading = true
      postAction('xxxxxxxxxxx', formData).then((res) => {
        if (res.code === 200) {
          this.success(res.message)
          this.fileList = []
          this.autoinquire()
          this.uploading = false
          this.uploadvisible = false
          console.log(this.fileList)
        } else {
          this.error(res.message)
          this.fileList = []
          this.uploading = false
          console.log(this.fileList)
        }
        if(this.uploading){
           setTimeout(()=>{
             this.uploading = false
           },9000)
        }
       
      })
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值