How to send file (i.e photo) to a REST API (i.e GPC Storage)


#1

Hi,

Is there a way to send a file over the internet to a public REST API? (maybe POST with fetch?)

Thanks,
Serban


#2

@serbans

Example Code Via Fetch :-
Step 1 . Get Image from Galary
Step 2. save Uri ( temp file )
Step 3. Send image via Api in Rest Client Class.
Step 4. Call Api Function From Other Class

Code for Sending Image :-
Step 3 :-

export const Calldetails_submitApi = (Token, image_uri) => {
    console.log('sending image 1')
    console.log('image_uri Api Call  :- ' + image_uri);
    // Assume "profile_image" is the name of the form field the server expects 
    let formdata = new FormData();
    formdata.append("profile_image", { uri: image_uri, name: 'image.jpg', type: 'multipart/form-data' })

    return fetch(Submit_Url, {
        method: 'post',
        headers: {
            "Authorization": Token,
            'Content-Type': 'multipart/form-data; boundary=someArbitraryUniqueString'
        },
        body: formdata
    }).then(response => {
        console.log("image uploaded")
        console.log(response)
        return response;
    }).catch(error => {
        console.log("failure in image upload Api")
        console.log(error)
        checkErrorStatus(error);
    })
}

Calling of Above function :-

Step 4 :- import And Calling .

import Api, {  Calldetails_submitApi } from '../../services/Api';


  //call api for get detail
  //Async function
  _Calldetails_submit(imageuri) {
    console.log('sending image 1 class')
    console.log('sending image 1 class :- ' + imageuri)
    Calldetails_submitApi(this.state.Token, imageuri)
      .then((res) => {
        console.log('sending image class 2')
        console.log(" Happy to see you Calldetails_submitApi and sent from Profile Page (~_~) ")
      })
      .catch((error) => {
        console.log("Sorry Image is not valid");
        alert(error)
      })

  }

closed #3

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.