使用场景,后端给了一个上传文件的接口/api/file/upload,方法类型为post,参数为{file: binary,type:string}.
上传文件需要设置请求头content-type.

项目使用的是umi4+antd5
请求拦截便在app.ts文件写。
export const request: RequestConfig = {
baseURL: '/api',
timeout: 5000,
// other axios options you want
errorConfig: {
errorHandler () {
},
errorThrower () { },
},
requestInterceptors: [
(url, options) => {
if (options.contentType) {
//修改请求头
options.headers['Content-Type'] = options.contentType;
}
return { url, options };
}
],
responseInterceptors: [],
};
上传参数示意

接口函数
import { request } from '@umijs/max';
export const fileUpload = (
params: any,
options?: { [key: string]: any },
) => request(
'/file/upload',
{
method: 'POST',
data: params,
...(options || {}),
contentType: 'multipart/form-data'
},
);
console.log(file, 'file');
cosUpload({
file: file.originFileObj,//文件对象
type: 'application'
}).then((res) => {
res?.data && setImageUrl(res.data);
}).finally(() => {
setLoading(false);
});

本文介绍了如何在umi4和antd5项目中使用axios进行文件上传,涉及接口/api/file/upload的POST请求,设置了content-type头,并演示了如何在app.ts文件中配置请求拦截器来处理上传参数和设置Content-Type。
1996

被折叠的 条评论
为什么被折叠?



