javascript - 如何使用远程 url 从 img 标签中检索图像并从中创建 File 对象
问题描述
脚步:
我有一个远程图片网址。
我从中生成了 img 标签。
现在我想读取这个 img 标签并将其转换为 File 对象,以便我可以将其发送到服务器进行上传。
方法一尝试:我已经尝试过fetch方法,直接尝试从远程url获取图片数据。
方法2试过:
clicked = () => {
const img = document.getElementById('someId');
const options = {
method: 'get',
headers: {
'Access-Control-Request-Headers': '*',
'Access-Control-Request-Method': '*',
},
mode: 'cors',
};
fetch(img.src, options)
.then(res => res.blob())
.then((blob) => {
const file = new File([blob], 'dot.png', blob);
console.log(file);
});
}
预期的输出是 File 对象。
解决方案
我在这里使用 axios 但主体应该相同:
const res = await axios.get(`/api/image/${imageId}`, {
responseType: 'arraybuffer'
});
const imgFile = new Blob([res.data]);
const imgUrl = URL.createObjectURL(imgFile);
忽略响应类型。
推荐阅读
- visual-studio-code - VSCODE。如何通过单击打开包含变量或 html 标记的文件?
- ios - 在 performDropWith 委托回调中访问源表视图
- c# - 更新(更新回退)具有子实体的实体列表的正确方法?
- php - 使用php将数据infile加载到oracle表中
- python - 通过使用 Python 计算行范围内的元素来创建新列
- python - 在循环中将一个列表的每个元素与第二个列表的四个元素相乘以获得新列表的函数
- drools - Drools 7.x 中“KnowledgeAgentConfiguration”属性的替代品是什么?
- python - 在 django 中从 rest API 运行 Python 脚本
- docker - 基于 Docker 的 graylog 权限
- laravel - 如何延迟每个被推入单个队列的作业