我试图开发一个函数来从 s3 返回文件,但它实际上并没有返回可以在浏览器中打开的工作文件:
export async function urlToFile (url : string, fileName: string) : Promise<File> {
let file = null
await axios.get(url).then(response => {
file = response.data
})
return new File([file], fileName)
}
但是,我在堆栈溢出上找到的这段代码确实有效,并且说如果我尝试的话,可以在浏览器中打开pdf。但是,问题是我必须手动添加 mimpe 类型,而且我不知道如何从下载网址获取它:
export function urltoFile(url, filename, mimeType){
if (url.startsWith('data:')) {
const arr = url.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[arr.length - 1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
const file = new File([u8arr], filename, {type:mime || mimeType});
return Promise.resolve(file);
}
return fetch(url)
.then(res => res.arrayBuffer())
.then(buf => new File([buf], filename,{type:mimeType}));
}
我更喜欢使用 axios,但如果它不可行,我愿意使用第二种方法,但需要帮助获取 mime 类型。
您可以将 axios 请求的响应类型指定为
blob
。然后,mime 类型将包含在响应标头中 content-type
。修改您的代码如下:
export async function urlToFile(url: string, fileName: string): Promise<File>{
const response = await axios.get(url, {
responseType: 'blob'
});
const fileData = response.data;
const mimeType = response.headers['content-type'];
return new File([fileData], fileName, {type: mimeType});
}