react將文件轉為base64上傳的示例代碼
更新時間:2023年09月06日 08:31:52 作者:ATWLee
本文主要介紹了react將文件轉為base64上傳的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
需求
將圖片、pdf、word、excel等文件進行上傳。圖片、pdf等調接口A、word、excel等附件調接口B。接口關于文件是base64格式的參數(shù)
業(yè)務場景
上傳資源,區(qū)分影像與附件
邏輯思路
- 使用原生input標簽,type='file',進行上傳
- 上傳后的回調,對文件進行分類,影像與附件
- 對文件進行base64編碼
- 執(zhí)行接口進行上傳
代碼實現(xiàn)
點擊input進行上傳,選擇文件后執(zhí)行onChange回調
<input type="file" multiple ref={uploadInputRef} onChange={uploadFileOnChange} />
對文件進行分類,我這里是通過type去判斷的
export const uploadFileOnChange = async (e: ChangeEvent<HTMLInputElement>) => { ? const files = e.target.files; ? // 將影像以及附件分類 ? const images: File[] = []; ? const attachments: File[] = []; ? for (const iterator of files ?? []) { ? ? if ( ? ? ? iterator.type.includes('sheet') || ? ? ? iterator.type.includes('excel') || ? ? ? iterator.type.includes('csv') || ? ? ? iterator.type.includes('word') ? ? ) { ? ? ? attachments.push(iterator); ? ? } else { ? ? ? images.push(iterator); ? ? } ? } };
對文件進行base64編碼
async function readFileAsDataURL(file: Blob) { ? const result_base64 = await new Promise<string>((resolve) => { ? ? const fileReader = new FileReader(); ? ? fileReader.readAsDataURL(file); ? ? fileReader.onload = () => ? ? ? typeof fileReader.result === 'string' && resolve(fileReader.result); ? }); ? return result_base64.split('base64,')[1]; } export const uploadFileOnChange = async (e: ChangeEvent<HTMLInputElement>) => { ? const files = e.target.files; ? // 將影像以及附件分類 ? const images: File[] = []; ? const attachments: File[] = []; ? for (const iterator of files ?? []) { ? ? if ( ? ? ? iterator.type.includes('sheet') || ? ? ? iterator.type.includes('excel') || ? ? ? iterator.type.includes('csv') || ? ? ? iterator.type.includes('word') ? ? ) { ? ? ? attachments.push(iterator); ? ? } else { ? ? ? images.push(iterator); ? ? } ? } ? const imageData: ImageData[] = []; ? const affixData: AffixData[] = []; ? for (const i of images) { ? ? const imgBase64 = await readFileAsDataURL(i); ? ? imageData.push({ ? ? ? name: i.name, ? ? ? imgBase64, ? ? }); ? } ? for (const i of attachments) { ? ? const affixBase64 = await readFileAsDataURL(i); ? ? affixData.push({ ? ? ? name: i.name, ? ? ? affixBase64, ? ? }); ? } ? return { ? ? imageData, ? ? affixData, ? }; };
拿到上一步返回的數(shù)據(jù)調接口
到此這篇關于react將文件轉為base64上傳的示例代碼的文章就介紹到這了,更多相關react將文件轉為base64進行上傳內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關文章
使用React-Router實現(xiàn)前端路由鑒權的示例代碼
這篇文章主要介紹了使用React-Router實現(xiàn)前端路由鑒權的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07