Search code examples
reactjstypescriptaxiosreact-native

Uploading Image Data from React Native Image Picker Using Axios


I have data retrieved from react-native-image-picker, which includes various properties such as fileName, fileSize, height, width, type, uri, and others. My objective is to upload this data as an image using FormData.

data: "/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2Qtan" => 90kb
fileName: "77677.jpg"
fileSize: 67542
height: 600
isVertical: true
originalRotation: 0
path: "/storage/emulated/0/Download/77677.jpg"
type: "image/jpeg"
uri: "content://media/external/images/media/18584"
width: 399
__proto__: Object

I'm encountering an issue with uploading the image data to the specified endpoint. Any insights or suggestions would be greatly appreciated.

const formData = new FormData();
formData.append("file", {
  uri: "file://" + response.uri,
  name: "MMM.jpg",
  type: response.type,
});

axios
  .post(
    "https://danskeclouddemo.com/api/file",
    { file: formData },
    {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "multipart/form-data",
      },
    },
  )
  .then((res) => {
    console.log(res);
  });

and this is BackEnd Postman Working good Postman collection

//====================== //====================== Edit

Some people talk about the problem from react native version after 0.61.5 in this link issues


Solution

  • Rather using, axiom use fetch simple, approach to upload, image

    this.setState({imageLoading:true})
        const credentials={
           userId:this.state.userId
        }
        try {
          let response = await fetch(
            'url',
            {
                'method': 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'multipart/form-data',
                },
                 body: createFormData(source, credentials)
            }
          );
          
          if (response.status == 200) {
                response.json().then(data => {
                
                switch (data.status) {
                    case 200:
                       
                        break;
                }
             });
          }else {
            this.setState({imageLoading:false ,isLoading:false})
                 }
        } catch (error) {
          this.setState({imageLoading:false,isLoading:false})
          console.error(error);
        }
    
    
    const createFormData=(image,body)=>{
    var data = new FormData();
    data.append(image, {
    uri:  Platform.OS === "android" ? image.uri : image.uri.replace("file://", ""), 
    name: `dummy${Date.now()}.jpg`,
    type: 'image/*'
    })
    
    
    Object.keys(body).forEach(key => {
        data.append(key, body[key]);
    });
    return data
    }