React Native: Save Image File on Local Filesystem or Send it to the Server with REST API.
Case1. Save an Image File on Local Filesystem
Because Image file is temporary saved on tmp directory just after it is picked by Image picker, the image file should be re-saved on the local filesystem permanently.
In this example, the variable “image" has a temporary file path, and the permanent file path is created and saved into the variable “cameraImageUri".
let cameraImageUri = '';
if (image) {
const fileName = image.split('/').pop();
cameraImageUri = FileSystem.documentDirectory + fileName;
try {
await FileSystem.moveAsync({ from: image, to: cameraImageUri });
} catch (err) {
throw new Error('Something went wrong on moving image file!');
}
}
If the file path should be sent to the server, you can send it with JSON format like that. (The line of “Authorization" is optional. )
const response = await fetch(serverUri, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + token, //optional.
},
body: JSON.stringify({
petName, //Enter other information you want to send.
cameraImageUri
}),
});
Case2. Send an Image File to the Server with REST API
Use “FormData()" to send an image file to the server with REST API.
var data = new FormData();
data.append('petName', petName);
data.append('image', {
uri: image,
name: 'cameraphoto.jpg', //dummy name
type: 'image/jpg',
});
Then send “data" to the server.
const response = await fetch(updatePetUri + '/' + id, {
method: 'POST',
headers: {
Authorization: 'Bearer ' + token, //optional
},
body: data,
});
Discussion
New Comments
No comments yet. Be the first one!