后端要求文件上传传递二进制文件???
参考 umi-request上传FormData类型问题_umi-request formdata-CSDN博客
import request from '@/utils/request';
// 批量下发(此接口使用from表单接收)
export async function issuance_audit_create(params: any) {
return request(`/create`, {
method: 'post',
data: params,
requestType: 'form',
});
}
/**
* request 网络请求工具
* 更详细的 api 文档: https://github.com/umijs/umi-request
*/
import ignoreTokenList from '@/utils/ignoreToken';
import { clearAuthAndLogout, getAuthToken } from '@/utils/Token';
import { notification } from 'antd';
import { formatMessage, history } from 'umi';
import { extend } from 'umi-request';
import { getSign } from './sign';
// 错误提示fun
const typeNoticeFun = (code: number | string) => {
notification.config({ maxCount: 1 }); // 当多个接口报错时只会显示一个错误提示
const errorText = formatMessage({ id: `res.code.${code}` });
let codeNum = Number(code);
if (codeNum === 400 || codeNum === 404 || codeNum === 405 || codeNum === 412) {
notification.warning({
message: `Warning`,
description: errorText,
});
} else if (codeNum >= 500 && codeNum <= 599) {
notification.error({
message: `Error`,
description: formatMessage({ id: `res.code.500` }),
});
} else if (codeNum === 15011 || codeNum === 15006 || codeNum === 15094) {
// // 离职黑名单,不展示
// notification.warning({
// message: `Warning`,
// description: text,
// });
} else if (codeNum !== 15041) {
// 请假不符合条件的提示语 只保留 表达式输出的提示语即可
notification.info({
message: `Info`,
description: errorText,
});
}
};
/**
* request异常处理程序
*/
const errorHandler = (error: any): Response => {
const { response } = error;
if (!response) {
notification.error({
description: '您的网络发生异常,无法连接服务器',
message: '网络异常',
});
return {} as Response;
}
return response;
};
/**
* 配置request请求时的默认参数
*/
const request = extend({
prefix: (<any>window).globalConfig.baseapi || '',
errorHandler, // 默认错误处理
// credentials: 'include', // 默认请求是否带上cookie
});
const FNoptions = (data: any) => {
let params = '';
if (data) {
for (const key in data) {
if (data.hasOwnProperty(key)) {
params += `${key}=${data[key]}&`;
}
}
}
// 去除最后一个&
params = params?.substring(0, params.length - 1);
return params;
};
// request拦截器, 改变url 或 options.
request.interceptors.request.use((url: any, options: any) => {
const token = getAuthToken();
const headers = {
lang: localStorage.getItem('umi_locale') ?? '',
// 'Content-Type': 'application/json',
// Accept: 'application/json',
// 设置请求头
sign: '',
timestamp: 0,
'tenant-id': '',
'app-id': '',
'account-id': '1',
'account-name': '1',
};
if (token) {
(headers as any).Authorization = token;
}
if (options.verifySign || ignoreTokenList.indexOf(history.location.pathname) !== -1) {
headers['tenant-id'] = sessionStorage.getItem('entry_tenant_id') || '1';
headers['app-id'] = '380615502080327680';
// 设置时间戳
headers.timestamp =
Math.round(new Date().getTime() / 1000) + Number(sessionStorage.getItem('offsetTime') || 0);
// 设置sign
if (options.method === 'post') {
// post
headers.sign = getSign(
headers.timestamp + (options.data ? JSON.stringify(options.data) : ''),
);
} else if (options.method === 'get') {
// get形式
let params = url.split('?')?.[1] ? url.split('?')?.[1] : FNoptions(options?.params);
if (params) {
headers.sign = getSign(headers.timestamp + params);
} else {
headers.sign = getSign(`${headers.timestamp}`);
}
}
}
return {
url,
options: {
...options,
headers,
},
};
});
export type dataResponse = {
code: number;
data: any;
message?: string;
};
/**
* 返回体异常处理程序
*/
const dataHandler = (resBody: dataResponse): dataResponse => {
const { code, message } = resBody;
if (code && code !== 200) {
typeNoticeFun(code, message);
}
return resBody;
};
// response拦截器, 处理response
request.interceptors.response.use(async (response) => {
if (response && response.status === 401) {
typeNoticeFun(401, '');
setTimeout(() => {
clearAuthAndLogout();
}, 3000);
} else if (response && response.status === 400) {
typeNoticeFun(400, '');
} else if (response && response.status === 403) {
typeNoticeFun(403, '');
return {} as Response;
} else if (response && response.status === 404) {
typeNoticeFun(404, '');
} else if (response && response.status === 405) {
typeNoticeFun(405, '');
} else if (response && response.status === 412) {
typeNoticeFun(412, '');
} else {
const data = await response.clone().json();
dataHandler(data);
}
return response;
});
export default request;
文件获取file // Upload onChange={handleChange}
// 上传文件改变时的状态
// const handleChange = ({ fileList }: { fileList: FileType[] }) => {
// props.onChange(fileList[0]?.originFileObj);
return;
};
const formSumbit = async (values: any) => {
let validate = values;
const formData = new FormData();
formData.append('file', validate?.file);
formData.append('contractTemplateId', editRecord?.value);
formData.append('partyACustomerId', validate?.partyACustomer?.value);
formData.append('partyACustomerName', validate?.partyACustomer?.label);
if (validate?.partyBCustomer?.value) {
formData.append('partyBustomerId', validate?.partyBCustomer?.value);
formData.append('partyBCustomerName', validate?.partyBCustomer?.label);
}
if (validate?.partyCCustomer?.value) {
formData.append('partyCCustomerId', validate?.partyCCustomer?.value);
formData.append('partyCCustomerName', validate?.partyCCustomer?.label);
}
issuance_audit_create(formData).then((res) => {
if (res.code === 200) {
setBtnDisabled(true);
message.success('成功');
modalForm.setFieldValue('bill_no', res.data);
} else {
message.error('失败');
setBtnDisabled(false);
}
});
return true;
};