一、文件手动上传,区别于用action=‘接口地址’的方法
①属性定义
const props: UploadProps = {
name: 'file',
//这个属性必须写
beforeUpload: file => {
setFileList([file]);
return false;
},
onRemove: file => {
//
},
fileList,
};
②组件代码
<Upload
{...props}
fileList={fileList}
onChange={handleChange}
>
{/* */}
</Upload>
③真正上传代码
const handleChange: UploadProps['onChange'] = async () => {
try {
const formData = new FormData();
//只能用beforeonload的参数当做遍历的值fileList
fileList.forEach(file => {
formData.append('file', file as RcFile);
});
//这里就可以调接口了,formData就是需要的参数
} catch (error) {
//
}
};
二、文件的下载
const downloadFile = async () => {
try {
//调接口
const res= await fetch('接口', {
method: 'POST',
body: JSON.stringify({参数对象}),
headers: {
//
},
});
if(res){
const blob = await res.blob();
const a = document.createElement('a');
document.body.appendChild(a);
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.download = 'name.doc'; //设置文件名
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href); // 释放 URL对象
document.body.removeChild(link);
}
} catch (error) {
//
}
};