How to upload image to server using ReactNative

I set the headers and body using fetch with Post to upload the image to the server. I get a 200 response code, but it does not load the image, but the rest of the data is loading.

Here is the body code:

export default function setRequestBody(imagePath){

    let boundry = "----WebKitFormBoundaryIOASRrUAgzuadr8l";

    let body = new FormData();

    body.append("--"+boundry+"\r\n");
    body.append("Content-Disposition: form-data; name=imageCaption\r\n\r\n");
    body.append("Caption"+"\r\n");
    body.append("--"+boundry+"\r\n");
    body.append("Content-Disposition: form-data; name=imageFormKey; filename =iimageName.pngg \r\n");
    body.append("Content-Type: image/png \r\n\r\n");
    body.append({uri : imagePath});
    // appened image Data Here
    body.append("\r\n");
    body.append("--"+boundry+"--\r\n");
    return body

}

Please, help. What mistake am I making. :(

+4
source share
2 answers

I found a solution:

let body = new FormData();
body.append('photo', {uri: imagePath,name: 'photo.png',filename :'imageName.png',type: 'image/png'});
    body.append('Content-Type', 'image/png');

fetch(Url,{ method: 'POST',headers:{  
     "Content-Type": "multipart/form-data",
     "otherHeader": "foo",
     } , body :body} )
  .then((res) => checkStatus(res))
  .then((res) => res.json())
  .then((res) => { console.log("response" +JSON.stringify(res)); })
  .catch((e) => console.log(e))
  .done()

** file name optional ...

+5
source

The problem is body.append({uri : imagePath});because the native JSC reaction does not support File and Blob, so you need to use libraries.

react-native-fetch-blob , , README.md

    RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
        Authorization : "Bearer access-token",
        otherHeader : "foo",
        'Content-Type' : 'multipart/form-data',
    }, [
    // element with property `filename` will be transformed into `file` in form data
    { name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64},
    // custom content type
    { name : 'avatar-png', filename : 'avatar-png.png', type:'image/png', data: binaryDataInBase64},
    // part file from storage
    { name : 'avatar-foo', filename : 'avatar-foo.png', type:'image/foo', data: RNFetchBlob.wrap(path_to_a_file)},
    // elements without property `filename` will be sent as plain text
    { name : 'name', data : 'user'},
    { name : 'info', data : JSON.stringify({
      mail : 'example@example.com',
      tel : '12345678'
    })},
  ]).then((resp) => {
    // ...
  }).catch((err) => {
    // ...
  })
+3

Source: https://habr.com/ru/post/1649742/


All Articles