'React native with Asp.net Core photo upload

I want to upload photos with React Native. My API attempt from Postman resulted in a positive. But React Native didn't make it.

React Native function

  uploadPhoto = async response => {
    const data = new FormData();
    data.append("image", {
      uri: response.uri,
      type: response.type,
      name: response.fileName,
      length:response.fileSize
    });
    const config={
      headers:{
        'Content-type':'multipart/form-data'
      }
    }
    axios
    .post('https://localhost:44337/api/values',JSON.stringify(data),config)
    .then(response=>{
      console.log(response);
    })
    .catch(error=>{console.log(error);})

  };

Asp.net Core side

 [HttpPost]
 public IActionResult Post([FromForm]PhotoModel bookData)
 {
             //installation codes
            return Ok();
 }

Model

  public class PhotoModel
    {
        public IFormFile image { get; set; }
    }

Result:Network Error



Solution 1:[1]

You can try in react native code. Hope helpful for you.

export const uploadImages = async (formData) => {
    try {
        let response = await axios({
            url: urlUploadImages,
            method: 'POST',
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE',
                'Access-Control-Allow-Headers': 'Access-Control-Allow-Methods, Access-Control-Allow-Origin, Origin, Accept, Content-Type',
                'Accept': 'application/x-www-form-urlencoded',
                'Content-Type': 'multipart/form-data',
                'Authorization': 'Bearer ' + global.TOKEN || 'Bearer ' + await AsyncStorage.getItem("@loggedInUserID:token"),
            },
            data: formData,
        });

        console.log('uploadImages API response', response)

        if (response.status === 401) {
            return global.UNAUTHORIZE;
        } else {
            // let json = await response;
            if (response.status === 200) {
                return response.data;
            } else {
                return global.FAIL;
            }
        }
    } catch (error) {
        console.log('Upload Failed', error);
    }
};

Solution 2:[2]

You don't have to change from form data back to JsonString. Send it right away.

.post('https://localhost:44337/api/values',data,config)

Solution 3:[3]

Remove json.stringify and verify that you set right values: const form = new FormData();

form.append('image', { uri: "file:///...", type: 'image/jpg', name: 'image.jpg', });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Deva Nath
Solution 2 hong developer
Solution 3 Oleg