2

Am using FormData() and Fetch() to Post and Image File to My Server After Tacking A picture on Android.

am using a public IP not posting to my localhost or anything and not using HTTPS, also using Genymotion Emulator.

My Code :

      var fd = new FormData();
      fd.append('image', {path:'file:///'}); 

      fetch(UPLOAD_URI,{
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        body: fd
        }).then(response => {
          console.log("image uploaded")
        }).catch(err => {
          console.log(err)
        })

Error Returned In the catch as the param err:

TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (fetch.js:441)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:542)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:378)
    at XMLHttpRequest.js:482
    at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
    at MessageQueue.__callFunction (MessageQueue.js:236)
    at MessageQueue.js:108
    at guard (MessageQueue.js:46)
    at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:107)

Is there some kind of permissions that am missing , whats the problem ?

Cheers,

3

1 Answer 1

0

for my case on android the following module helped me to solve this issue as it was using java to send my file to the server and to be fetched using $_FILES in PHP :

npm install react-native-file-transfer-android

My Code :

var FileTransfer = require('react-native-file-transfer-android');

const UPLOAD_URI = "http://< IP / Domain>/index.php"


  makeUuid()
  {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for( var i=0; i < 5; i++ )
          text += possible.charAt(Math.floor(Math.random() * possible.length));

      return text;
  }

  sendImageToServer(data){

        var uuid = this.makeUuid();
        FileTransfer.upload({
          uri: data,
          uploadUrl: UPLOAD_URI,
          fileName: 'temp.jpg',
          mimeType: 'image/jpg',
          headers: {
            'Accept': 'application/json'
          },
          data: {
            name:uuid
          }
            }, (err, res) => {
              if(err) {
                console.error(err);
              } else {
                console.log(res);
              }
          });
   }

  saveImage(imgDate){

    let states = {camera:false};
    states[this.state.ActiveImage] = imgDate.path;
    this.sendImageToServer(imgDate.path);
    this.setState({
      ...states
    });




  }

Cheers.

Sign up to request clarification or add additional context in comments.

Comments

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.