我有一堆DataUrl-s,我想将其转换为FileList。
根据文档,FileList是只读的,并且这样的事情不起作用:
const fileList = new FileList()
那么,有没有办法从FileList
-s创建DataUrl
?
P.S。我们的目标是在将文件上传到服务器之前对其进行修改。
P.P.S.请不要建议使用File[]
而不是FileList
,因为我们使用的库不接受。
答案 0 :(得分:1)
有一个不错的解决方案,看起来不错。
将文件数组视为FileList。
代码如下:
public dataUrlToFileList(dataUrls: string[], fileNames: string[]): FileList {
const fileArray: File[] = [];
for (let index = 0; index < dataUrls.length; index++) {
const dataUrl = dataUrls[index];
const fileName = fileNames[index];
// Converting content to Blob
const blobObject = this.dataUrlToBlob(dataUrl);
// Converting Blob to file
const file = new File([blobObject], fileName);
fileArray.push(file);
}
// Converting array with file to filelist and passing to uploader
return fileArray as unknown as FileList; // < -------------- MAGIC HAPPENS HERE
}
private dataUrlToBlob(dataUrl: string): Blob {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
const byteString = atob(dataUrl.split(",")[1]);
// separate out the mime component
const mimeString = dataUrl.split(",")[0].split(":")[1].split(";")[0];
// write the bytes of the string to an ArrayBuffer
const ab = new ArrayBuffer(byteString.length);
// create a view into the buffer
const ia = new Uint8Array(ab);
// set the bytes of the buffer to the correct values
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
const blob = new Blob([ia], { type: mimeString });
return blob;
}