文件上传 antd Upload
- 入口
let params = {
riskProjectInfoId:'adsfdsfsdgfdsfgfhd',
riskProjectNumber:'NUMBER-001',
}
let propsUpload = UploadUtil.getPropsUpload(url.importRiskAttachmentLibrary,'inspectLibraryFile',params);
<Upload {...propsUpload}>
<Button>
<Icon type="upload" /> {'检查库导入'}
</Button>
</Upload>
- UploadUtil.js
getPropsUpload: (action, name = 'file', data={}) => {
const props = {
name,
action: action,
data,
onChange: UploadUtil.propsUploadOnChange,
};
return props;
},
propsUploadOnChange: info => {
console.log('propsUploadOnChange.info', info);
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (info.file.status === 'done') {
message.success(`${info.file.name} file uploaded successfully`);
} else if (info.file.status === 'error') {
message.error(`${info.file.name} file upload failed.`);
}
}
文件下载
- 入口
<Button
onClick={()=>{
FileUtil.export(url.exportRiskAttachmentLibrary,{})
}}
>
<Icon type="export" /> {'检查库导出'}
</Button>
- FileUtil.js
/**
* 导出文件
* @param {*} url
* @param {*} params
*/
export: async (
url,
params,
config = {
responseType: 'blob' // TODO important 解决文件乱码问题
}
) => {
console.log('file export start');
const response = await exportFile(url, params, config);
FileUtil.downloadZipByResponse(response);
console.log('file export end');
},
getFileNameByResponse: response => {
const { headers } = response;
const contentDisposition = headers['content-disposition'];
const contentDispositionArr = contentDisposition.split(';');
let filename = '未命名';
for (let i = 0; i < contentDispositionArr.length; i++) {
if (contentDispositionArr[i].indexOf('filename') > -1) {
filename = decodeURI(contentDispositionArr[i].split('=')[1]) || '未命名';
}
}
return filename;
},
downloadZipByResponse: response => {
const { headers, data } = response;
const contentType = headers['content-type'];
const filename = FileUtil.getFileNameByResponse(response);
var anchor = document.createElement('a');
document.body.appendChild(anchor);
var blob = new Blob([data], {
type: contentType
});
var blobUrl = window.URL.createObjectURL(blob);
anchor.href = blobUrl;
anchor.download = filename;
anchor.click();
window.URL.revokeObjectURL(blobUrl);
anchor.remove();
},
- apiFile.js
import { requestFile } from '~/utils/request';
// exportFile
export function exportFile(url, params, config) {
return requestFile.post(url, params, config);
}
- request.js
const requestFile = axios.create({
baseURL: '/'
});
requestFile.interceptors.response.use(
response => {
if (response.status >= 200 && response.status < 300) {
return response; // response
}
const error = new Error(response.statusText);
error.response = response;
throw error;
},
error => {
console.log('error', error);
return Promise.reject(error);
}
);
参考:
网友评论