文件上传
文件上传参数有 Request Payload 和 Form Data 两种格式(如图), 通过Content-Type 来区分
Request Payload
Form Data
设置两种格式的参数
Content-Type: application/x-www-form-urlencoded
或者不设置 Content-Type 为 formdata
Content-Type: application/json 或者 multipart/form-data 为 formdata
原生 js 上传(好处是没有中间层, 没有设置不设置超时)
拦截器上传
一定要看看 utils/request.js 内的 axios 实例有没有设置 timeout: Infinity (在大文件上传时文件会中断上传)
const service: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_TINTMCE_BASE_URL,
withCredentials: false, // send cookies when cross-domain requests
timeout: Infinity // request timeout
});
使用
import shareLibService from '@/api/modules/shareLibService'
shareLibService.importFile(fd)
下载文件的两种方法
第一种是获取到二进制流之后进行节点下载(这里省去了项目中的二进制请求)
function downloadBlobFile(result: any, fileName: string, type = 'xlsx') {
const blob = new Blob([result]);
const downloadElement = document.createElement('a');
const href = window.URL.createObjectURL(blob); // 创建下载的链接
downloadElement.href = href;
downloadElement.download = `${fileName}.${type}`; // 下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); // 点击下载
document.body.removeChild(downloadElement); // 下载完成移除元素
window.URL.revokeObjectURL(href); // 释放掉blob对象
}
一般上面的方法是可以下载的,但是有时候浏览器可以直接打开下载的链接,依照上面的函数却不能下载,可以试试第二种方法
export function downloadFile(url: string) {
const Authorization = `${token}`;
fetch(url, {
method: 'get', // 'post'
headers: {
'Content-Type': 'application/json',
Authorization: Authorization,
},
// body: JSON.stringify(params)
})
.then((res) => res.blob())
.then((blob) => {
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = `下载.xlsx`;
document.body.appendChild(link);
link.click();
});
}