本篇主要涉及两个简单的小功能,一个是读取网络图片为File对象,一个是读取远程的Json文件。
1、一个简单的需求,就是将一张网络图片转换成File对象。
话不多说,直接上代码:
// 将url转成file对象
const responseFile = await fetch(imgUrlPath, { mode: 'no-cors' });
const blob = await responseFile.blob();
// 从 URL 提取文件名
const fileName = imgUrlPath.substring(imgUrlPath.lastIndexOf('/') + 1);
// 将 Blob 转换为 File 对象
const fileOne = new File([blob], fileName, { type: blob.type });
// 打印 File 对象
console.log(" File:", fileOne);
2、如何将一个网络的json文件读取出来呢?请看下面代码:
const loadJsonFile = (imgUrlPath) => {
console.log('imgUrlPath:', imgUrlPath);
fetch(imgUrlPath)
.then(response => response.json())
.then(json => {
console.log('json:', json);
return json;
})
.catch(error => console.error('Error:', error));
}
全部评论