33 lines
2.6 KiB
TypeScript
33 lines
2.6 KiB
TypeScript
|
|
// Expo fetch accepts Blob parts, while the Android picker returns local URI parts.
|
||
|
|
// Read only local files through the native file reader; HTTP uploads still use
|
||
|
|
// the authenticated API transport and its redirect/cancellation policy.
|
||
|
|
type LocalFile = {uri:string;name?:string;type?:string};
|
||
|
|
function readLocalFile(file:LocalFile,signal:AbortSignal):Promise<Blob>{
|
||
|
|
if(!/^(?:file|content):\/\//i.test(file.uri))return Promise.reject(new Error('附件地址无效,请重新选择文件。'));
|
||
|
|
return new Promise((resolve,reject)=>{
|
||
|
|
if(signal.aborted){reject(new Error('文件读取已取消。'));return;}
|
||
|
|
const request=new XMLHttpRequest();let settled=false;
|
||
|
|
const finish=(error?:Error,blob?:Blob)=>{if(settled)return;settled=true;signal.removeEventListener('abort',abort);request.onload=request.onerror=request.onabort=request.ontimeout=null;if(error)reject(error);else resolve(blob!);};
|
||
|
|
const abort=()=>{request.abort();finish(new Error('文件读取已取消。'));};
|
||
|
|
request.onload=()=>{const blob=request.response;if((request.status!==0&&request.status!==200)||!(blob instanceof Blob)||!blob.size){finish(new Error('无法读取本地附件,请重新拍摄或选择文件后重试。'));return;}finish(undefined,blob.type===file.type||!file.type?blob:blob.slice(0,blob.size,file.type));};
|
||
|
|
request.onerror=()=>finish(new Error('无法读取本地附件,请重新拍摄或选择文件后重试。'));
|
||
|
|
request.onabort=()=>finish(new Error('文件读取已取消。'));
|
||
|
|
request.ontimeout=()=>finish(new Error('读取本地附件超时,请重新选择文件。'));
|
||
|
|
signal.addEventListener('abort',abort,{once:true});
|
||
|
|
try{request.open('GET',file.uri,true);request.responseType='blob';request.timeout=30000;request.send();}
|
||
|
|
catch{finish(new Error('无法读取本地附件,请重新拍摄或选择文件后重试。'));}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
export async function readableMultipart(body:FormData,signal:AbortSignal):Promise<FormData>{
|
||
|
|
const entries=Array.from((body as FormData & {entries():IterableIterator<[string,string|Blob|LocalFile]>}).entries());
|
||
|
|
const local=(value:unknown):value is LocalFile=>!!value&&typeof value==='object'&&!(value instanceof Blob)&&typeof (value as LocalFile).uri==='string';
|
||
|
|
if(!entries.some(([,value])=>local(value)))return body;
|
||
|
|
const prepared=new FormData();
|
||
|
|
for(const [name,value] of entries){
|
||
|
|
if(local(value))prepared.append(name,await readLocalFile(value,signal),value.name||'attachment');
|
||
|
|
else if(value instanceof Blob)prepared.append(name,value,(value as File).name||'attachment');
|
||
|
|
else prepared.append(name,value);
|
||
|
|
}
|
||
|
|
return prepared;
|
||
|
|
}
|