首页 > 解决方案 > 如何在 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 类型。

标签: reactjsreact-native

解决方案


这很简单:

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")

我花了很长时间才弄明白,但现在它是有道理的。

我希望对某人有所帮助!


推荐阅读