How To Upload Image On Server Using Reactnative
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 upl
Solution 1:
I've found the solution:
let body = newFormData();
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...
Solution 2:
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 : 'example@example.com',
tel : '12345678'
})},
]).then((resp) => {
// ...
}).catch((err) => {
// ...
})
Solution 3:
I've found the solution to Upload the Image on server in React Native:
const formdata = new FormData();
formdata.append('image[]', {
name: 'test.' + imageurl?.type?.substr(6),
type: imageurl?.type,
uri:
Platform.OS !== 'android'
? 'file://' + imageurl?.uri
: imageurl?.uri,
});
const res = await axios.post(url, formdata, {
headers: {
Accept: '*/*',
'Content-type': 'multipart/form-data',
},
});
Solution 4:
//First Install and import Image-piker //install
npm i react-native-image-picker
//import
import * asImagePickerfrom'expo-image-picker';
//then
const [image, setImage] = React.useState(null);
const [Type,setType]=React.useState('')
//Get the image
const pickImage = async () => {
let result = awaitImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if (!result.cancelled) {
// extract the filetypesetType(result.uri.substring(result.uri.lastIndexOf(".") + 1));
setImage(result.uri);
}
};
//show image return
<Viewstyle={{flex:1, alignItems: 'center', justifyContent: 'center' }}><Buttontitle="Ecolher Foto"onPress={pickImage} />
{image && <Imagesource={{uri:image }} style={{width:150, height:150 }} />}
</View>
//UpLoad Image
var validatinoApi ='https://seusite.com/OOP/';
var headers={
'Accept':'application/json',
"Content-Type": "multipart/form-data",
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Origin':'*',
'crossDomain': 'true',
'Host': 'https://seusite.com/OOP/',
'Origin': 'https://origem.com',
};
/*'crossDomain': 'true',*/varData={
image:image,
namefoto: `photo.${namefoto}`,
type: `image/${Type}`
};
fetch(validatinoApi,
{
method:'POST',
headers:headers,
body:JSON.stringify(Data)
}).then((response)=>response.json())
.then((response)=>{
if(response.statusCode==200){
//Do something
}
Post a Comment for "How To Upload Image On Server Using Reactnative"