react文件下载/上传(记录)

1,865 阅读1分钟

忘了多久前从别的地方拉下的了(如有侵犯烂糟的麻烦告知)

下载:

responseType: 'blob', // 表明返回服务器返回的数据类型

headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' // 'Content-Type': 'multipart/form-data', },

返回的response

const blob = new Blob([response.data])

const downloadElement = document.createElement('a');

const href = window.URL.createObjectURL(blob); // 创建下载的链接

downloadElement.href = href;

downloadElement.download = downloadName; // 下载后文件名

document.body.appendChild(downloadElement);

downloadElement.click(); // 点击下载

document.body.removeChild(downloadElement); // 下载完成移除元素

window.URL.revokeObjectURL(href); // 释放掉blob对象

上传:

headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }