reactjs - 如何在 React Native 中使用 Axios 将图像发送到具有 Blob 类型的服务器?
问题描述
我尝试从图库中选择一张图片,我得到如下数据:
{
"exif":null,
"localIdentifier":"9F983DBA-EC35-42B8-8773-B597CF782EDD/L0/001",
"filename":"IMG_0003.JPG",
"width":500,
"modificationDate":null,
"mime":"image/jpeg",
"sourceURL":"file:///Users/vichit/Library/Developer/CoreSimulator/Devices/3BBFABAC-2171-49AA-8B2B-8C2764949258/data/Media/DCIM/100APPLE/IMG_0003.JPG",
"height":500,
"creationDate":"1344451932"
}
这次我想用Axios把这张图片发送到Blob类型的服务器上。
我不知道如何将这张图片转换为 Blob 类型。
解决方案
这很简单:
async function uploadToServer(sourceUrl) {
// first get our hands on the local file
const localFile = await fetch(sourceUrl);
// then create a blob out of it (only works with RN 0.54 and above)
const fileBlob = await localFile.blob();
// then send this blob to filestack
const serverRes = await fetch('https://www.yourAwesomeServer.com/api/send/file', { // Your POST endpoint
method: 'POST',
headers: {
'Content-Type': fileBlob && fileBlob.type,
},
body: fileBlob, // This is your file object
});
const serverJsonResponse = await serverRes.json();
// yay, let's print the result
console.log(`Server said: ${JSON.stringify(serverJsonResponse)}`);
}
像这样跑uploadToServer("file:///Users/vichit/Library/Developer/CoreSimulator/Devices/3BBFABAC-2171-49AA-8B2B-8C2764949258/data/Media/DCIM/100APPLE/IMG_0003.JPG")
我花了很长时间才弄明白,但现在它是有道理的。
我希望对某人有所帮助!
推荐阅读
- ejabberd - Ejabberd 服务器设置
- java - 如何简单地读取我创建的 .txt 文件并计算其行数
- function - Powershell - 将 Export-ToCSV 参数添加到函数
- python - 如果行在熊猫中匹配,则在列之间匹配行并创建新列
- python - 将 python 输出发送到烧瓶服务器
- python - 如何将固定数量的 int 字符转换为字符串?
- r - 通过一个值多个嵌套列表列,然后通过一个分组变量在嵌套列表列中添加
- typescript - 具有特定键和值的通用类型
- php - 我的 php 代码不会显示 phpmyadmin (sql) 数据库的结果
- security - 遵循 mtls 迁移步骤时,Istio 与种类 PeerAuthentication 不匹配