使用axios上传文件、下载(导出)文件

    xiaoxiao2023-10-23  164

    上传文件

    上传文件需要将请求头的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); })

    下载(导出)文件

    axios({ method: 'post', url: 'http://127.0.0.1/detail/list/export?mealcomeTime=1558691428000&rand=9848', responseType: 'blob', data: {"materialId":7079075,"beginDate":"2019-05-01 00:00:00","endDate":"2019-05-24 23:59:59","shipUnitId":4,"firstUnitId":4,"secondUnitId":4,"customerIds":[],"sortType":"","sortField":"","pageIndex":1,"pageSize":50}, headers: { sessionId: 'c22824d846c94a459bf60cf286349399', sign: 'a29b3e56399e58d91459be2e64a8dbf9ecbfcd8097af08fb38ede3c64b15a889', } }).then(response => { 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); })

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

    content-disposition

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

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

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

    相关文档

    https://github.com/axios/axios/issues/895 I misunderstood the concept of CORS. Access-Control-Expose-Headers is a response header issued by the service. This issue has nothing to do with axios. The service should allow Content-Disposition header to be exposed for the client, in my case it does. Due to HTTP access control CORS in browsers, the client application needs a proxy cors (in my case an express middleware) to read the header value. Apologies for misunderstanding.

    最新回复(0)