1

I'm trying to upload an image from my app to API, but it didn't responded by the server, but another data which is text is sent successfully, can anyone help me?

Response from the image picker

{"fileName": "rn_image_picker_lib_temp_62670a6c-c6a8-47a6-ae8f-2696455d141b.jpg", "fileSize": 82214, "height": 800, "type": "image/jpeg", "uri": "content://com.talikasih.imagepickerprovider/cacheDir/rn_image_picker_lib_temp_62670a6c-c6a8-47a6-ae8f-2696455d141b.jpg", "width": 379}

and this is the data

const datas = new FormData();
datas.append('images', payload.image)

Here is the axios

axios({
      method: 'POST',
      url: API_NO_PARAM_CONFIG.createCampaign,
      headers: {
        Authorization: `Bearer ${e}`,
      },
      data: {
        datas,
      },
    })

1 Answer 1

4

Here is the solution. First save the selected image in one of your state variable. For example create a state variable called "selectedImage" as below:

const [selectedImage, setSelectedImage] = useState(null);

Now, when you select image set selected image in your state variable like this:

    ImagePicker.launchImageLibrary(options, (response) => {
      if (response.uri) {
        setSelectedImage(response);
      }
    });

Now create FormData as below:

  const datas = new FormData();

  datas.append('images', {
    name: selectedImage.fileName,
    type: selectedImage.type,
    uri:
      Platform.OS === 'android' ? selectedImage.uri : selectedImage.uri.replace('file://', ''),
  });

And pass as below :

axios({
  method: "POST",
  url: API_NO_PARAM_CONFIG.createCampaign,
  headers: {
    Authorization: `Bearer ${e}`,
    "Content-Type": "multipart/form-data", // add this
  },
  datas, //pass datas directly
});
Sign up to request clarification or add additional context in comments.

3 Comments

what should I do with the response from the image picker, can I just pass it just like that?
@user14593851 I updated the answer. Please check.
thanks for ur answer but still.. it doesn't work, the request sent but the image doesn't get updated in the server

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.