I am using react-native-image-crop-picker I can select the image from gallery but when trying to upload to server via form-data, but the image is not uploading to server, its showing blank on server.Can anyone suggest me how to upload multiple image to server using react-native-image-crop-picker?It would be so appreciable.Thanks.
4
votes
3 Answers
2
votes
Create a service to handle file uploads
import axios from 'axios';
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const uploadService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Baerer '+jwtKey;
}
try{
return axios.post(
url,
data,
config
);
}catch(error){
console.warn(error);
}
}
In your View create an upload handler, I have added a sample below
import { uploadService } from '../services/UploadService';
showProfileCropper = (data) => {
ImagePicker.openCropper({
path: data.uri,
freeStyleCropEnabled: true,
cropping: true,
width: data.width,
height: data.height,
includeExif: true,
}).then(image => {
this.setState({
image: { uri: image.path, width: image.width, height: image.height, mime: image.mime },
images: null
});
this._uploadProfile(image);
}).catch(e => {
//console.warn(e)
});
}
_uploadProfile = async (data) => {
const jwtKey = '';
this.setState({ uploading: true });
let uploadData = new FormData();
uploadData.append('pageId', this.state.pageId);
uploadData.append('submit', 'ok');
uploadData.append('uploadfile', { type: data.mime, uri: data.path, name: data.path.split("/").pop() });
uploadService(uploadData, '', jwtKey).then((resp) => {
this.setState({ uploading: false });
//console.warn(resp.data);
if (resp.data.success) {
//this._getPageDataAfterUpload();
}
}).catch(err => {
//console.warn(err);
});
}
render(){
...........
<TouchableOpacity
style={styles.profileImgContain}
onPress={() => { this.showProfileCropper(this.state.image); }}
>
<Text>Choose Image</Text>
</TouchableOpacity>
...........
}
Please let me know If you have any difficulties
0
votes
Assuming that your back-end server accepts file as a parameter for images and you are trying to upload multiple images to the server and on server, miltiple images handling is implemented and you are using axios for API handling, you can do something like:
const images = await ImageCropPicker.openPicker({
mediaType: 'photo',
compressImageQuality: 0.4
});
const data = new FormData();
images.forEach((image, index) => {
data.append(`file[${index}]`, {
uri: Platform.OS === 'ios' ? `file:///${image.path}` : image.path,
type: 'image/jpeg',
name: 'image.jpg'
});
});
axios({
url: 'imageUploadUrl',
method: 'POST',
data,
headers: { 'Content-Type': 'multipart/form-data' }
}).then((response) => {
console.log('image upload response: ', response)
}).catch((error) => {
console.log('image upload error: ', error)
});
Please do not forget to replace the imageUploadUrl with your server API url.
0
votes
In my case, I was getting 400 error because for some reason in android, the filename field was empty. So I generated filename is its unavailable.
name: image.filename || `${Date.now()}.jpg`,
Example:
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: cropping,
multiple: true,
})
.then((selImages) => {
if (selImages && selImages.length == 1) {
let output = images.slice();
output[index] = {
uri: selImages[0].path, // for FormData to upload
type: selImages[0].mime,
name: selImages[0].filename || `${Date.now()}.jpg`,
};
console.log('ImagePicker.openPicker: output', output);
onChange(output);
} else {
const output = selImages.map((image) => ({
uri: image.path,
type: image.mime,
name: image.filename || `${Date.now()}.jpg`,
}));
onChange(output);
console.log('ImagePicker.openPicker: output', output);
}
})
.catch((e) => console.error('Image Group: ', e));