ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Tuesday, December 13, 2022

[FIXED] How to upload Image on server using ReactNative

 December 13, 2022     android, ios, react-native, reactjs   

Issue

I am setting headers and body , Using fetch with Post to upload image on server.I am getting the response code 200 but it is not uploading image but rest of the Data is getting uploaded.

Here is the code of body:

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 I am making. :(


Solution

I've found the 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()

** filename is optional...



Answered By - Rajeev Upadhyay
Answer Checked By - - Candace Johnson (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix