How to transfer photos to x-www-form-urlencoded immediately after taking a picture EXPO

1.9k views Asked by At

I want to take a picture, save it to an album and send the image right away. (Do not select from album.)

There is no problem in taking the current picture, saving it in an album and checking the uri.

but the x-www-form-urlencoded sending process does not work properly.

I think there may be a problem with the format of sending the API.

postman is also attached. (No problem in Postman.)

 takePictureAndCreateAlbum = async () => {
    const { uri } = await this.camera.takePictureAsync();
    console.log('uri', uri);
    const asset = await MediaLibrary.createAssetAsync(uri);
    console.log('asset', asset);

    const filename = asset.filename;

    MediaLibrary.createAlbumAsync('Expo', asset)

      // POST API
      .then(() => {

        var file = new FormData();
        file.append({file: uri});

        return fetch(/* API_URL */, { 
              method: 'POST',
              headers:{

                  'Content-Type':'application/x-www-form-urlencoded',
                  'Accept': 'application/json'
             } , body : file} )

         .then((response) => response.text())
              .then((responseData) => {
                  console.log(responseData);
              })
              .done();

      })
      .catch(error => {
        Alert.alert('An Error Occurred!')
      });
  };

Postman Header

Postman Body

1

There are 1 answers

5
Nick Rameau On

When appending to a FormData instance, the first parameter is the field name (What your server will be getting as an object key for this file), the second one is an object in the following form:

{
  uri: // The uri you received from the camera,
  type: // The file type (i.e.: image/png),
  name: // The file name
}

In your case, it would be like this:

// Split the uri by `.` (periods)
const uriParts = uri.split('.');
// Grab the file type at the end of the uri
const fileType = uriParts[uriParts.length - 1];

file.append('picture', {
  uri,
  type: `image/${fileType}`,
  name: 'FILE-NAME.${fileType}`
});

Also, when sending files, your Content-Type header should be multipart/form-data