Upload image to server with XMLHttpRequest and FormData in React-Native - android

I am trying to upload image to server with progress by using the example provided by:
https://gist.github.com/Tamal/9231005f0c62e1a3f23f60dc2f46ae35
I checked some tutorials, the code should works. But the uri in Android show uri
uri: content://media/external/images/media/4985
The URI come from the component
https://github.com/jeanpan/react-native-camera-roll-picker
The URI should be
file://....
So, why the upload code not working.
How can I convert the
content://... to file://.... to make it possible to upload image to server in React-native? or does my assumed is correct?

I am using react-native-image-picker to get image from library. I have written following code in one method name as selectPhoto() to select image from library.
selectedPhoto = () => {
//Open Image Picker
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
};
ImagePicker.showImagePicker(options, (response) => {
//console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
let source = {uri :response.uri};
console.log(source.uri);
this.setState({
profilePhoto: source
});
}
}); }
This will give me uri of selected image and I have set in state variable. then write following code to upload image.
var profiePicture = {
uri: this.state.profilePhoto.uri,
type: 'image/jpg', // or photo.type image/jpg
name: 'testPhotoName',
}
// API to upload image
fetch('http://www.example.com/api/uploadProfilePic/12345', {
method: 'post',
headers:{
'Accept': 'application/json',
'content-type': 'multipart/form-data',
},
body: JSON.stringify({
'profile_pic' : profiePicture
})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
This code is working in one of the my project.

Related

Ionic Cordova Camera Image Upload Issue

I am using MediaCapture library but getting 403. Below is my code:
MediaCapture.captureImage(options).then(
async (data: any) => {
const contents: any = await Filesystem.readFile({
path: data[0].fullPath,
});
setPreviewImage(contents);
let blobData: any = {};
let formdata = new FormData();
formdata.append(
"file",
`data:${data[0].type};base64,${contents.data}`
);
const response = (await axios.post(
Endpoints.userCover,
formdata
)) as ServerResponse;
if (response.status) {
console.log(response);
console.log("-------------------- IMAGE Camera");
}
},
(err) => console.error(err, " error")
);
enter image description here
Getting 403 on MediaCapture library when using Camera but it's working when selecting image from the android Gallery.

Upload a file from react native image picker to server

can someone tell me what i m doing wrong i keep getting error 400 bad request, i can't seem to figure out how to send the image i tried to send the path, the filename and the mime but it's not working this is my request:
const [image,setImage]=useState(null)
const[filename,setFileName]=useState(null)
const sendpic=async ()=>{
await ImagePicker.openCamera({
mediaType:'photo',
width: 300,
height: 400,
cropping: false,
}).then(image => {
setImage(image['path']);
const paths=image['path']
const filename=paths.substring(paths.lastIndexOf('/')+1);
setFileName(filename);
console.log(filename)
console.log(image)
const data=new FormData();
data.append('image',filename)
data.append('title','3aslemajiti')
const headers={
Accept:'application/json',
'Content-Type':'multipart/form-data',
}
try{
const response= axios.post('http://192.168.1.19:8000/Sends/',data,{headers:headers})
alert('yess!!!!!');
}
catch (error) {
// handle error
alert(error.message);
}
});
};
and this is my model:
from django.db import models
# Create your models here.
class Send(models.Model):
title = models.CharField(max_length=255)
image=models.ImageField(default ='null')
def __str__(self):
return self.title
how do i write the request so it is accepted by the server?
data.append('image', {
uri: filename,
name: 'test.jpg',
type: 'image/jpeg'
});
Image upload format should be this and please check file url should be correct.
"uri": "file:///Users/user/Library/Developer/CoreSimulator/Devices/33198C8D-55D3-4555-B9B5-DC1A61761AAF/data/Containers/Data/Application/B5067299-1CD2-4000-8935-59B59ED447F6/tmp/871EB6D5-2408-4A10-8DE7-EE52B1855ECD.jpg"
this is url for image. it should be like this.
const data = new FormData();
data.append("uploadFile", {
name: filename,
type: filetype,
uri:
Platform.OS === "android"
? fileuri
: fileuri.replace("file://", "")
});
var url = uploadDoc
axios.post(url, data, {headers: {
"Content-Type": "multipart/form-data",
Accept: "application/json",
Authorization: authToken
}})
.then((res) => {
})
.catch((err) => {
})

Uploading image to firebase in react native: undefined is not a function

As the title says, I'm trying to upload Image to firebase in react native. I'm using react-native-image-picker and firebase modules for that. My code goes as: (Only including the "main" parts for clarity)
import ImagePicker from 'react-native-image-picker';
...
//called on pressing a button
onChooseImagePress = async () => {
let result = await ImagePicker.open({ //error occurs here
takePhoto: true,
useLastPhoto: true,
chooseFromLibrary: true
});
if (!result.cancelled) {
this.uploadImage(result.uri, "test-image")
.then(() => {
Alert.alert("Success");
})
.catch((error) => {
Alert.alert(error);
});
}
}
uploadImage = async (uri, imageName) => {
const response = await fetch(uri);
const blob = await response.blob();
var ref = firebase.storage().ref('images').child("userName/" + imageName);
return ref.put(blob);
}
....
Issue:
I am getting this error: undefined is not a function. Here's a screenshot of the same:
I'm not sure what it even means, since ImagePicker has an open function. Please note that I have provided the desired permissions. So it is not an issue due to that. Please help me resolve this. Thanks...
Are you using React-native ImagePicker? There is no open in the API document.
API Reference of react-native-image-picker
This is the default example of getting the value of the selected image you want.
import ImagePicker from 'react-native-image-picker';
// More info on all the options is below in the API Reference... just some common use cases shown here
const options = {
title: 'Select Avatar',
customButtons: [{ name: 'fb', title: 'Choose Photo from Facebook' }],
storageOptions: {
skipBackup: true,
path: 'images',
},
};
/**
* The first arg is the options object for customization (it can also be null or omitted for default options),
* The second arg is the callback which sends object: response (more info in the API Reference)
*/
ImagePicker.launchImageLibrary(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
});
}
});

React-Native multipart photo upload not working in android

I'm trying to send/upload image file to my back-end serve using fetch multipart upload in react-native, but fetch multipart form data upload is not working for android, however I tried different examples.
Image upload multipart form data API is based on php and its working for iOS react-native app.
I am using react-native-photo-upload library for taking image.
storePicture(PicturePath:string) {
console.warn(PicturePath);
if (PicturePath) {
const apiUrl = `${Constants.APIHOST}updateprofileimage.php`;
// Create the form data object
var data = new FormData();
data.append('profileimage', { uri:PicturePath, name: 'profileimage.jpg', type: 'image/jpg/jpeg' });
data.append('accesstoken', this.state.user.sAccessToken);
data.append('react-native', 1);
// Create the config object for the POST // You typically have an OAuth2 token that you use for authentication
const config = { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'multipart/form-data;' }, body: data };
fetch(apiUrl, config)
.then(responseData => { // Log the response form the server
// Here we get what we sent to Postman back
console.warn(`response:${responseData}`);
})
.catch(err => {
console.warn(err);
});
}}
Here is the example how I am calling storePicture() function.
<PhotoUpload onResizedImageUri={
avatar => {
if (avatar) {
this.storePicture(avatar.path);
}
}}
>
<Image source={{uri: this.state.user.sProfileImageUrl}} style={{resizeMode:"cover", marginTop:8.0, backgroundColor:'transparent', height:120.0, width:120, borderRadius:60.0, borderWidth:0.0, borderColor:'transparent'}}/>
</PhotoUpload>
uploadProfileImage = async (image:var) => {
this.setState({
loading: true
});
var RNFS = require('react-native-fs');
const path = Style.IS_IOS ? image.uri : image.path;
var fileName = path.split('/').pop();
var fileType = fileName.split('.').pop();
var filePath = Style.IS_IOS ? path : 'file://' + path;
const apiURL = `${Constants.APIHOST}updateprofileimage.php`;
const formData = new FormData();
formData.append('accesstoken', this.state.user.sAccessToken);
formData.append('reactnative', 1);
formData.append('profileimage', {
uri:filePath,
name: fileName,
type: `image/${fileType}`,
});
try {
const response = await fetch(apiURL, {
body: formData,
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json',
},
})
const json = await response.json()
this.handleUploadImageResponse(json);
} catch (err) {
this.setState({
loading: false
},console.log('catch Error: '+ err));
}
}
I am answering my own question as I haven't found any valid answer for the sake of other users, who are facing same issue.
Please let me know if I can improve my answer/post or in case any help is needed from me.
Image Upload to an API by Multipart FormData
uploadPicture = () => {
console.log(
"Image Upload urI = " + JSON.stringify(this.state.imageSourceUri.uri)
);
this.setState({ loading: true });
const form = new FormData();
form.append("fileToUpload", {
uri: this.state.imageSourceUri.uri,
type: "image/jpg",
name: "12334"
});
fetch("http://119.82.97.221/HPBSProjectApi2/api/HPBS/PostFormData", {
method: "post",
body: form
})
.then(response => response.json())
.then(response => {
console.log("response = " + response);
this.setState({
loading: false
});
});
};
the problem is the type field in the FormData, use mime to resolve it. Images must be image/jpeg.
const formData = new FormData();
formData.append("image",{..., name, uri, type: mime.getType(uri)}));

react-native android Could not retrieve file for contentUri http://192.168.108.18:8180/app/upload/storag/app_head/201610131627080535.jpg

[enter image description here][1]
When I used react-native fetch formData upload a image , in iOS it worked,but in android it console.log 'Could not retrieve file for contentUri http://192.168.108.18:8180/app/upload/storag/app_head/201610131627080535.jpg'.
Could someone please let me know how can I solve it?
It is my code:
var formData = new FormData();
formData.append('owner_id',this.state.owner_id)
formData.append('head_portraits',{uri:this.state.head_portraits,type:'image/jpeg'||'image/png',name:'headImage.jpg'});
formData.append('owner_name',this.state.owner_name)
formData.append('sex',this.state.sex)
formData.append('mobile',this.state.mobile)
fetch('http://192.168.108.18:8180/app/app/owner/guest/addOwner?', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body:formData
}).then((response) => response.json()
).then((responseJson) => {
console.log(responseJson);
if (responseJson.status === '0000'){
Alert.alert('提示','保存个人信息成功!',[
{
text: '确定'
}
])
}
})
.catch((error) => {
console.log('错误:' + error);
})
}
formData.append('head_portraits', {
uri: this.state.head_portraits,
type:'image/jpeg'||'image/png',
name:'headImage.jpg'
});
to
formData.append('head_portraits',{
uri:'file://' + this.state.head_portraits,
type:'image/jpeg'||'image/png',
name:'headImage.jpg'
});
You need to add this file:// before the this.state.head_portraits for Android. In iOS, it works without file://.

Categories

Resources