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. :(
To handle image uploads we need to set the encoding type to multipart/form-data which means we need to format our data differently. Thus the createFormData function. This function will go ahead and take the image we selected and add it to the photo field of the form data with the required info.
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...
The problem is body.append({uri : imagePath});
because react native JSC does not support File and Blob, so you have to use libraries.
react-native-fetch-blob has very good support for this, example from its 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 : '[email protected]',
tel : '12345678'
})},
]).then((resp) => {
// ...
}).catch((err) => {
// ...
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With