2022年6月16日
今天联调文件上传和下载,遇到两个坑,这个或许与使用的请求框架有关,我这里使用的是umi-request。
在umiRequest中,如果你想在请求的响应中获取response,那么就需要在参数中设置一个配置,getResponse
。
而且它的header是map,不能直接header['key']
的方式拿值,而且你在调试的时候会发现header是个空对象,这会令你觉得后端没给你返回响应头数据或者你会认为浏览器的安全机制导致你无法访问响应头。
import request from 'umi-request';
const options = {
responseType: 'arrayBuffer' // blob
};
const data = {
id: 2000
}
// request.get(url, { ...options, params: data, getResponse: true })
request.post(url, { ...options, data, getResponse: true })
.then({resposne, data} => {
// 拿到响应头部的数据
// const disposition = response.headers?.['content-disposition']; // 这种方式不行,因为headers是一个Map结构,得使用map的get方法才行
const disposition = response.headers?.get('content-disposition');
})
浏览器会有安全机制不允许你访问响应的头的某些数据,比如你的自定义响应头之类的数据,这是需要后端配合一下,让浏览器允许你访问这个响应头的数据。
后端设置access-control-expose-headers,有的框架默认就可以让你访问响应头的这个数据。
response.setHeader("Access-Control-Expose-Headers","Content-Disposition");// 可以添加多个,用,隔开就行,比如:Content-Disposition,Content-Type
antd 组件文件上传
antd 的upload组件默认是有上传机制的,如果你想不用它的上传机制,可以改写一下。
import {
Button,
Col,
Form,
message,
Row,
Upload
} from 'antd';
const [data, setData] = useState(null);
const props = {
name: 'file',
action: '',
headers: {
"content-type": "multipart/form-data"
},
accept: 'image/png',
maxCount: 1,
beforeUpload: file => {
const isPNG = file.type === 'image/png';
console.log('file', file);
if (!isPNG) {
message.error(`${file.name} is not a png file`);
}
return isPNG || Upload.LIST_IGNORE;
},
customRequest(options ) {
const { onSuccess, file } = options;
onSuccess();
},
onChange(info) {
const fmData = new FormData();
fmData.append('myFile', info.file.originFileObj);
fmData.append('code', '123456789');
setData(fmData);
}
};
const upload = () => {
if (data) {
dispatch({
type: 'model/upload',
payload: data,
callback: (response) => {
if (!response.success) {
alert('错误:' + response.msg);
return;
}
}
});
}
};
return (
<Form>
<Row gutter={24} justify="center">
<Col span={22} style={{ textAlign: 'left' }}>
<Form.Item name="select" label="选择">
<Upload {...props}>
<Button type="default">请选择文件</Button>
</Upload>
</Form.Item>
</Col>
</Row>
<Row gutter={24} justify="center">
<Col span={24} style={{ textAlign: 'center' }}>
<Button style={{ margin: '0 8px', width: 200 }} type="primary" onClick={() => upload()}>
上传
</Button>
</Col>
</Row>
</Form>
)
上次更新时间: 10年18月2023日 01时57分53秒