4

I try to select a picture from the gallery, and I got data like below:

{  
   "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"
}

For this time, I want to send this picture to the server with Blob type using Axios.

I don't know how to convert this picture to a Blob type.

1

1 Answer 1

6

It's simple:

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)}`);
}

And run like uploadToServer("file:///Users/vichit/Library/Developer/CoreSimulator/Devices/3BBFABAC-2171-49AA-8B2B-8C2764949258/data/Media/DCIM/100APPLE/IMG_0003.JPG")

It took me forever to figure it out, but it makes sense now.

I hope that helps someone!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.