1.引入U(xiǎn)pload
''
<Upload {...uploadProps} fileList={DownloadFile} getValueFromEvent={normFile}>
<Button icon={<UploadOutlined />}>上傳文件</Button>
</Upload>
''
2.配置上傳文件屬性
文件上傳按鈕屬性
''
const uploadProps = {
name: 'file',
action: 'XXX',
method: 'POST',
accept: '.jpeg ,.jpg ,.png,.pdf,.docx,.mp4,.mp3,.xls,.doc,.xlsx',
headers: { Authorization: Bearer ${accessToken}
},
data: { user_id: accountInfo.id },
disabled: false,
FileList: DownloadFile,
showUploadList: {
// showPreviewIcon: '預(yù)覽',
showDownloadIcon: true,
showRemoveIcon: accountRoles.includes('city_role')
? false
: !accountRoles.includes('zone_role'),
removeIcon: (
<img
className="removeIcon"
src="https://pppses-1-1253940515.cos.ap-shanghai.myqcloud.com/assets/close-circle.svg"
/>
),
},
onDownload: (file: any) => {
filePublicFunc.downloadInstitutionSingleFile(file);
},
onRemove: (file: any) => {
filePublicFunc.removeFile(file);
if (DownloadFile.length > 1) {
filePublicFunc.removeFile(file);
} else {
message.warning('至少保留一條');
}
},
onChange: (info: any) => {
if (info.fileList.length >= 1) {
setDownloadFile(info.fileList);
}
try {
if (info.file.status === 'done') {
if (info.file.response.code === 2000) {
filePublicFunc.getFileInfo().then((res: any) => {
setDownloadFile(res);
dispatch({
type: AssessmentResults/setFileLength
,
payload: { Data: res.length },
});
dispatch({
type: AssessmentResults/setIsFileUp
,
payload: { Data: true },
});
message.success('上傳成功');
});
} else {
message.error('上傳失敗');
setDownloadFile(info.fileList);
}
}
if (info.file.status === 'error') {
message.error('上傳失敗');
setDownloadFile(info.fileList);
}
if (info.file.status === 'uploading') {
dispatch({
type: AssessmentResults/setIsFileUp
,
payload: { Data: false },
});
}
} catch (error) {
console.log(error);
}
},
};
const normFile = (e: any) => {
if (Array.isArray(e)) {
return e;
}
if (e.file.status === 'done') {
return e.file.response.data.fullPath;
}
return e && e.fileList;
};
const filePublicFunc = new FileFunc(
'XXX',
accessToken,
accountInfo && accountInfo.hasOwnProperty('id') ? accountInfo : ACCOUNT_ONLY,
false,
);
''
3.封裝操作上傳文件class
''
import { message } from 'antd';
import request from '@/utils/request';
''
''
export class FileFunc {
URL: string; // 用戶傳入的路由
Token: string; // 用戶傳入的token
Role: any; // 用戶的一下基本信息
isChangeList: boolean;
constructor(URL: string, Token: string, Role: any, isChangeList: boolean) {
this.URL = URL;
this.Token = Token;
this.Role = Role;
this.isChangeList = isChangeList;
}
// 刪除指定報(bào)告Method
removeFile = async (File: any) => {
const REMOVE_FILE: any = await request.get(this.URL, {
params: { delete_id: File.id },
});
if (REMOVE_FILE.code === 2000) {
this.isChangeList = true;
message.success(REMOVE_FILE.message);
} else {
message.error('刪除失敗');
}
};
// 獲取當(dāng)前用戶下的所有上傳文檔
getFileInfo = async () => {
try {
const RED_ALL_FILE = await request.get(this.URL, {
params: { user_id: this.Role.id },
});
if (RED_ALL_FILE.code === 2000) {
RED_ALL_FILE.data.forEach((item: any, index: number) => {
RED_ALL_FILE.data[index]['status'] = 'done';
RED_ALL_FILE.data[index]['name'] = item.file_name;
});
return RED_ALL_FILE.data;
}
} catch (error) {
console.log(error);
}
};
downloadInstitutionSingleFile = async (File: any) => {
const DOWNLOAD_ALL_FILE: any = await request.get(this.URL, {
params: { id: File.id },
responseType: 'blob',
getResponse: true,
});
const hide = message.loading('下載中...', 0);
try {
if (DOWNLOAD_ALL_FILE) {
setTimeout(hide, 500);
const CD = DOWNLOAD_ALL_FILE.response.headers.get('content-disposition').split(';');
let CD_TEMP: string = '';
for (let i = 0; i < CD.length; i += 1) {
if (!CD[i].indexOf('filename=')) CD_TEMP = CD[i];
}
const FILE_EXTENSION = CD_TEMP.split('.')[CD_TEMP.split('.').length - 1];
let fileName = '未識(shí)別的文件名';
if (File.name) {
fileName = ${File.name}
;
} else {
fileName = 未識(shí)別的文件.${FILE_EXTENSION}
;
}
this.convertRes2Blob(DOWNLOAD_ALL_FILE.data, fileName);
message.success('下載成功');
} else {
message.error('下載失敗');
}
} catch (error) {
console.log(error);
}
};
convertRes2Blob(data: any, filename = '下載內(nèi)容') {
const blob = new Blob([data], { type: 'application/octet-stream' });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, decodeURI(filename));
} else {
const blobURL = window.URL.createObjectURL(blob);
const tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = blobURL;
tempLink.setAttribute('download', decodeURI(filename));
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(blobURL);
}
}
getMessageSuccess = (notice: string) => {
message.success(notice);
};
getMessageError = (notice: string) => {
message.error(notice);
};
}
''