How can you upload an image/jpeg file to a presigned url on s3, while sending Content-Type multipart/form-data?

Viewed 447

I may have some misunderstanding this works. Essentially I would like to upload images to a presigned url generated via S3. Currently I am sending POST requests with the following headers:

      "Content-Type": 'image/jpeg',
      "file": {
        uri: some_image,
        type: 'image/jpeg',
        name: `some_image.jpeg`
      }

So this works. However I'm finding the upload very very slow. The images are 2-3 MBs each. On wifi it's much quicker but on a mobile network, it can take up to 30 seconds. I've read changing the Content-Type to multipart/form-data will help accelerate the upload. However when I modify it to Content-Type: form-data, the metadata on s3 will be set to Content-Type: form-data. But I want the Content-Type: form-data to be image/jpeg as this image will be served on the internet. If not set to Content-Type: image/jpeg, the browser will simply download the file to a directory.

The below doesn't work as the metadata on the image on S3 has metadata Content-Type: multipart/form-data

      "Content-Type": 'multipart/form-data',
      "file": {
        uri: some_image,
        type: 'image/jpeg',
        name: `some_image.jpeg`
      }

I'm using React. My axios function looks like this.

export default function HTTP({ method, url, data, params, headers }) {  
  return new Promise((resolve, reject) => {    
    const query = {
      method: method,
      url: url,
    }
    if (params) {
      query.params = params
    }
    if (headers != null) {
      query.headers = headers;
    }
    if (data) {
      query.data = data;
    }   
    axios({...query, timeout: 30000}).then(function (response) {
      resolve(response);
    })
      .catch((error) => {
        if (error) {
          NavigatorService.navigate('Back');
        }
        reject(error)

      })
  })
}

Thanks

1 Answers

Hi @readdit55 you need to create form data like.

Example:
       headers: 
           "Content-Type": 'multipart/form-data',
       body: 
          createFormData({
             'uri': some_image,
             'type': 'image/jpeg',
             'name'': `some_image.jpeg`
          });

**Method to create form data:**
       const createFormData = (objects) => {
             const data = new FormData();
             Object.keys(objects).forEach((key,Index)=>{
                 data.append(key, body[key]);
             });
             return data;
       })
Related