使用antd的Upload組件實(shí)現(xiàn)文件上傳下載

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);
};
}
'
'

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市痰娱,隨后出現(xiàn)的幾起案子懊烤,更是在濱河造成了極大的恐慌酝碳,老刑警劉巖伴网,帶你破解...
    沈念sama閱讀 216,651評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件逃沿,死亡現(xiàn)場離奇詭異透揣,居然都是意外死亡济炎,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門淌实,熙熙樓的掌柜王于貴愁眉苦臉地迎上來冻辩,“玉大人,你說我怎么就攤上這事拆祈。” “怎么了倘感?”我有些...
    開封第一講書人閱讀 162,931評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵放坏,是天一觀的道長。 經(jīng)常有香客問我老玛,道長淤年,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,218評(píng)論 1 292
  • 正文 為了忘掉前任蜡豹,我火速辦了婚禮麸粮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘镜廉。我一直安慰自己弄诲,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評(píng)論 6 388
  • 文/花漫 我一把揭開白布娇唯。 她就那樣靜靜地躺著齐遵,像睡著了一般。 火紅的嫁衣襯著肌膚如雪塔插。 梳的紋絲不亂的頭發(fā)上梗摇,一...
    開封第一講書人閱讀 51,198評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音想许,去河邊找鬼伶授。 笑死断序,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的糜烹。 我是一名探鬼主播逢倍,決...
    沈念sama閱讀 40,084評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼景图!你這毒婦竟也來了较雕?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,926評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤挚币,失蹤者是張志新(化名)和其女友劉穎亮蒋,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體妆毕,經(jīng)...
    沈念sama閱讀 45,341評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡慎玖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評(píng)論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了笛粘。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片趁怔。...
    茶點(diǎn)故事閱讀 39,731評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖薪前,靈堂內(nèi)的尸體忽然破棺而出润努,到底是詐尸還是另有隱情,我是刑警寧澤示括,帶...
    沈念sama閱讀 35,430評(píng)論 5 343
  • 正文 年R本政府宣布铺浇,位于F島的核電站,受9級(jí)特大地震影響垛膝,放射性物質(zhì)發(fā)生泄漏鳍侣。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評(píng)論 3 326
  • 文/蒙蒙 一吼拥、第九天 我趴在偏房一處隱蔽的房頂上張望倚聚。 院中可真熱鬧,春花似錦凿可、人聲如沸惑折。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽唬复。三九已至,卻和暖如春全肮,著一層夾襖步出監(jiān)牢的瞬間敞咧,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評(píng)論 1 269
  • 我被黑心中介騙來泰國打工辜腺, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留休建,地道東北人乍恐。 一個(gè)月前我還...
    沈念sama閱讀 47,743評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像测砂,于是被迫代替她去往敵國和親茵烈。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容