react-nativezendesk-api

how to upload images using Zendesk Upload API


I'm using the function below to upload images on zendesk. Zendesk requires image to be in binary to be uploaded and getting the blob image method is working when I'm uploading on Firebase. These function gets a response 201 but when you check the image, is just a white square. I think image got corrupted during the upload.

imageUri is returned from expo-image-picker like this below:

file:/data/user/0/host.exp.exponent/cache/ExperienceData/.../ImagePicker/8543faa5-b996-46cd-9554-ce9afb61385b.jpg

const uploadImages = async (imageUri) => {

    try {
        const filename = getFilenameFromImagePicker(imageUri);
    
        const resImg = await fetch(imageUri);
        const blobImg = await resImg.blob();
    
        const response = await axios.post(`uploads?filename=${filename}`, {
            blobImg
        }, {
            auth: {
                username: membersEmail + '/token',
                password: ZENDESK_API_KEY
            },
            headers: {
                'Content-Type': 'application/binary',
            }
        })
    
        return response.data;
    }
    catch (error) {
        captureException(error);
        return null;
    }

}

What is the best way to change the image to binary so it can be uploaded to zendesk?

Below is the curl statement from Zendesk's documentation for uploading images

curl "https://{subdomain}.zendesk.com/api/v2/uploads?filename=myfile.dat&token={optional_token}" \
  -data-binary @file.dat \
  -v -u {email_address}:{password} \
  -H "Content-Type: application/binary" \
  -X POST

Solution

  • After alot of testing, I was able to make it work. Posting here the answer I come up with incase someone else has the same problem.

    async function uploadImages (imageUri) {
            // first get our hands on the local file
            const localFile = await fetch(imageUri);
        
            // 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': application/binary,
                },
                body: fileBlob, // This is your file object
            });
        
            const serverJsonResponse = await serverRes.json();
            return serverJsonResponse;
        }