A jpeg image uploaded from an iPhone to S3 is not readable. But works on photoshop

Viewed 415

I'm trying to upload a jpeg image from an iOS device to S3 using a presigned url. Here's what I'm doing:

const file = {
  uri: imageURL,
  type: 'image/jpeg'
};

const formData = new FormData();
formData.append('photo', file);
formData.append('Content-Type', 'image/jpeg');

const response = await axios({
  method: 'PUT',
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  url: s3PreSignedURL,
  data: formData
});

(The app is in react native and I use react-native-camera to take the photo.)

The problem is the image gets uploaded. When I download it and try to view on my mac it says The file could not be opened. But if I open it in Photoshop it works. Any idea what's going on?

You can find a sample image here: https://s3-ap-southeast-1.amazonaws.com/eyesnapdev/scans/1509856619481-71809992-b818-4637-93f1-9a75b6588c2c.jpg

2 Answers

Seems you aren't using formData to send the image, rather it should be like this:

const file = {
  uri: imageURL,
  type: 'image/jpeg'
};

const formData = new FormData();
formData.append('photo', file);
formData.append('Content-Type', 'image/jpeg');

const response = await axios({
  method: 'PUT',
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  url: s3PreSignedURL,
  data: formData // not **file**
});

Your uploaded image is saving whole multipart form data and contains the following information as well (Open your s3 jpg image in a text editor to see):

--K_B9dYtGXt4.LjeMIncq0ajcL6vDRYqD1hRiwoIOJzPKYTVi8jTYT_f07RZw37Om1NJwGi content-disposition: form-data; name="photo" content-type: image/jpeg

s3 upload expects only data of file to be uploaded in post not a multipart form.

After digging through React native core, I think following code should work. I haven't tried it myself yet though:

fetch(s3PreSignedURL,{
    method:"PUT",
    headers: {
      'Content-Type': 'image/jpg'
    },
    body:{uri:imageURL}
});

or using axios:

axios({
  method: 'PUT',
  headers: {
    'Content-Type': 'image/jpg'
  },
  url: s3PreSignedURL,
  body:{uri:imageURL} 
});
Related