React native how to upload multiple images to server (backend) - file-upload

for single Image upload working but multiple images upload not working
const data = new FormData();
//sending data to backend in the form of array
data.append("media_files", [{
uri: item.uri,
type: item.mime,
name: item.name || `filename${i}.jpg`,
}]);

Working Properly now
const [selectedImages, setSelectedImages] = useState(imageData)
const data = new FormData();
//images selected from image picker(react-native-image-crop-picker) library
selectedImages.forEach((item, i) => {
data.append("media_files[]", {
uri: item.uri,
type: "image/jpeg",
name: item.filename || `filename${i}.jpg`,
});
});

Related

React Native - How to rename camera roll image file name

I'm having a problem using #react-native-community/cameraroll.
Here's my code:
const handleSaveImageToDevice = async () => {
try {
const uri = await captureRef(viewRef, {
format: 'jpg',
quality: 0.8,
});
const image = CameraRoll.save(uri, {
type: 'photo',
album: 'Generated Image',
});
} catch (e) {
return e;
}
};
As seen in the code I used captureRef to save react elements with ref as image.
The behavior is working as expected. If the user clicks the save button the image will be saved to the designated folder. But the problem is it saves random file name. I want to rename it like for example "generated_image".
When you are capturing there is option for image file name:
const uri = await captureRef(viewRef, {
format: 'jpg',
quality: 0.8,
fileName: 'generated_image'
});
Refer below link:
https://github.com/gre/react-native-view-shot/issues/116#issuecomment-1155523609
I forgot to update this but I already found a way to fix my problem using third party library react-native-fs
viewShot?.current?.capture().then((data) => {
RNFS.writeFile(
RNFS.CachesDirectoryPath +
`/generated-image.jpg`,
data,
'base64',
).then((success) => {
return CameraRoll.save(
RNFS.CachesDirectoryPath +
`/generated-image.jpg`,
{
type: 'photo',
album: 'testing',
},
);
});
});

Uploading large video files on background in react native

I need to upload large video files in the background.
What is the best way to achieve this?
I tried using this library (react-native-background-upload). But the problem is, I can't send any other data along with the video file. The API expects the following data:
{
projectId: number,
title: string,
video: file,
};
This is the piece of code to send the files with multipart using the library:
const options = {
url: url,
path: pathToVideoFile,
method: 'POST',
field: 'video',
type: 'multipart',
};
Are there any alternatives that I can use? Can react-native-background-fetch be used for this use case?
in react-native-background-upload
you can use parameters in options to send additional data
Additional form fields to include in the HTTP request. Only used when type: 'multipart
const options = {
url: url,
path: pathToVideoFile,
method: 'POST',
field: 'video',
type: 'multipart',
parameters : {
key1: "value1",
key2: "value2",
}
};
you can see all options params here here
you can install react-native-compressor package which is made by me
Installation
yarn add react-native-compressor
Usage
import {Video} from 'react-native-compressor';
const headers={
'Content-Type': '',
}
const uploadResult = await Video.backgroundUpload(
"http://w.hbu50.com:8080/hello.mp4",
fileUri,
{httpMethod: 'PUT', headers},
(written, total) => {
onProgress({
status: 'uploading',
progress: written / total,
uploading: true,
});
},
);

Upload images from React Native to LoopBack

I need to upload a selection of images that user picked from CameraRoll to the LoopBack Component Storage. The thing is that the component storage is working fine, because I can upload and download the files through Postman. But, when I try to upload from react native to loopback, it always returns "No file content upload" with http status 400.
I read a lot of people talking about it and tried everything and none worked for me.
First, I am taking the images from the CameraRoll and my images array looks like this:
[
{
exists: 1,
file: "assets-library://asset/asset.JPG?id=3FF3C864-3A1A-4E55-9455-B56896DDBF1F&ext=JPG",
isDirectory: 0,
md5: "428c2e462a606131428ed4b45c695030",
modificationTime: 1535592967.3309255,
size: 153652,
uri: null
}
]
In the example above I just selected one image.
I transformed to Blob, then I got:
[
{
_data: {
blobId: "3FF3C864-3A1A-4E55-9455-B56896DDBF1F",
name: "asset.JPG",
offset: 0,
size: 153652,
type: "image/jpeg"
}
}
]
So I tried a lot of things after this, tried to send the blob itself as the request body, tried to append to a form data and send the form data, but it doesn't matter the way I try, I always get the "No file content upload" response.
I also tried the example from Facebook, didn't work: https://github.com/facebook/react-native/blob/master/Libraries/Network/FormData.js#L28
The way I am trying now:
In my view:
finalizarCadastro = async () => {
let formData = new FormData();
let blobs = [];
for(let i=0;i<this.state.fotos.length;i++){
let response = await fetch(this.state.fotos[i]);
let blob = await response.blob();
blobs.push(blob);
}
formData.append("files", blobs);
this.props.servico.criar(formData);
}
And the function that send to my server:
criar: (servico) => {
this.setState({carregando: true});
axios.post(`${REQUEST_URL}/arquivos/seila/upload`, servico, {headers: {'content-type': 'multipart/form-data'}}).then(() => {
this.setState({carregando: false});
this.props.alertWithType("success", "Sucesso", "Arquivo salvo com sucesso");
}).catch(error => {
this.setState({carregando: false});
console.log(error.response);
this.props.alertWithType("error", "Erro", error.response.data.error.message);
})
}
I found the solution. So the problem was actually not the code itself, the problem was sending multiple files at the same time. To fix everything, I did this:
this.state.fotos.forEach((foto, i) => {
formData.append(`foto${i}`, {
uri: foto,
type: "image/jpg",
name: "foto.jpg"
});
})
this.props.servico.criar(formData);
And my function that sends the request to the server:
criar: (servico) => {
this.setState({carregando: true});
axios.post(`${REQUEST_URL}/arquivos/seila/upload`, servico).then((response) => {
this.setState({carregando: false});
this.props.alertWithType("success", "Sucesso", "Arquivo salvo com sucesso");
}).catch(error => {
this.setState({carregando: false});
this.props.alertWithType("error", "Erro", error.response.data.error.message);
})
},
So you don't need to set the Content-Type header to multipart/form-data and don't need to transform the images to blob, actually you just need the uri of each one, and I think the type and name attributes are opcional.

How to get jpg image from heic format in react native

I am picking photos from gallery and upload to server but since few days I noticed that some photos have extension heic and browsers can't render those images.
1. Is there a way to extract photos from uploaded heic?
2. How in react native I can get jpeg from this format?
You can convert it on the server side, with the help of this awesome lib Tifig.
https://github.com/monostream/tifig
You can also use API's like https://cloudconvert.com/formats/image/heic to convert either on server side or on the mobile (client side).
I'm assuming you are using react-native-image-picker, which is the community library and most used one.
Actually is not necessary to install another module, just grab always the uri from the response and update the filename in case you are having a heic image. Code example:
const options = {
title: 'Select Avatar',
storageOptions: {
skipBackup: true,
path: 'images'
},
noData: true,
quality: 1,
mediaType: 'photo'
};
ImagePicker.showImagePicker(options, imgResponse => {
this.setState({ imageLoading: true, avatarMediaId: null });
if ((imgResponse.didCancel) || (imgResponse.error)) {
this.setState({ imageLoading: false });
} else {
let source = {};
let fileName = imgResponse.fileName;
if (Platform.OS === 'ios' && (fileName.endsWith('.heic') || fileName.endsWith('.HEIC'))) {
fileName = `${fileName.split(".")[0]}.JPG`;
}
source = { uri: imgResponse.uri, fileName };
this.uploadImage(source);
}
});
Here's my solution: I am using react-native-image-crop-picker.
In my case, the server doesn't accept if a filename is .HEIC, telling me to use .png or .jpg
So I just:
image.filename.replace(/HEIC/g, 'jpg')
To give you a whole picture:
const formData = new FormData();
formData.append('file', {
uri: image.path,
name: image.filename.replace(/HEIC/g, 'jpg'),
type: image.mime,
});
return await axios.post(`/avatar/${id}`, formData);

How to upload file to server using react-native

I am developing a app where i need to upload an image to the server. Based on the image i get a response which i need to render?.
Can you please help me how to upload an image using react-native?.
There is file uploading built into React Native.
Example from React Native code:
var photo = {
uri: uriFromCameraRoll,
type: 'image/jpeg',
name: 'photo.jpg',
};
var body = new FormData();
body.append('authToken', 'secret');
body.append('photo', photo);
body.append('title', 'A beautiful photo!');
var xhr = new XMLHttpRequest();
xhr.open('POST', serverURL);
xhr.send(body);
My solution is using fetch API and FormData.
Tested on Android.
const file = {
uri, // e.g. 'file:///path/to/file/image123.jpg'
name, // e.g. 'image123.jpg',
type // e.g. 'image/jpg'
}
const body = new FormData()
body.append('file', file)
fetch(url, {
method: 'POST',
body
})
I wrote something like that. Check out https://github.com/kamilkp/react-native-file-transfer
I have been struggling to upload images recently on react-native. I didn't seem to get the images uploaded. This is actually because i was using the react-native-debugger and network inspect on while sending the requests. Immediately i switch off network inspect, the request were successful and the files uploaded.
I am using the example from this answer above it works for me.
This article on github about the limitations of network inspect feature may clear things for you.
Just to build on the answer by Dev1, this is a good way to upload files from react native if you also want to show upload progress. It's pure JS, so this would actually work on any Javascript file.
(Note that in step #4 you have to replace the variables inside the strings with the type and file endings. That said, you could just take those fields out.)
Here's a gist I made on Github: https://gist.github.com/nandorojo/c641c176a053a9ab43462c6da1553a1b
1. for uploading one file:
// 1. initialize request
const xhr = new XMLHttpRequest();
// 2. open request
xhr.open('POST', uploadUrl);
// 3. set up callback for request
xhr.onload = () => {
const response = JSON.parse(xhr.response);
console.log(response);
// ... do something with the successful response
};
// 4. catch for request error
xhr.onerror = e => {
console.log(e, 'upload failed');
};
// 4. catch for request timeout
xhr.ontimeout = e => {
console.log(e, 'cloudinary timeout');
};
// 4. create formData to upload
const formData = new FormData();
formData.append('file', {
uri: 'some-file-path', // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
type: `${type}/${fileEnding}`, // example: image/jpg
name: `upload.${fileEnding}` // example: upload.jpg
});
// 6. upload the request
xhr.send(formData);
// 7. track upload progress
if (xhr.upload) {
// track the upload progress
xhr.upload.onprogress = ({ total, loaded }) => {
const uploadProgress = (loaded / total);
console.log(uploadProgress);
};
}
2. uploading multiple files
Assuming you have an array of files you want to upload, you'd just change #4 from the code above to look like this:
// 4. create formData to upload
const arrayOfFilesToUpload = [
// ...
];
const formData = new FormData();
arrayOfFilesToUpload.forEach(file => {
formData.append('file', {
uri: file.uri, // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
type: `${type}/${fileEnding}`, // example: image/jpg
name: `upload.${fileEnding}` // example: upload.jpg
});
})
In my opinion, the best way to send the file to the server is to use react-native-fs package, so install the package
with the following command
npm install react-native-fs
then create a file called file.service.js and modify it as follow:
import { uploadFiles } from "react-native-fs";
export async function sendFileToServer(files) {
return uploadFiles({
toUrl: `http://xxx/YOUR_URL`,
files: files,
method: "POST",
headers: { Accept: "application/json" },
begin: () => {
// console.log('File Uploading Started...')
},
progress: ({ totalBytesSent, totalBytesExpectedToSend }) => {
// console.log({ totalBytesSent, totalBytesExpectedToSend })
},
})
.promise.then(({ body }) => {
// Response Here...
// const data = JSON.parse(body); => You can access to body here....
})
.catch(_ => {
// console.log('Error')
})
}
NOTE: do not forget to change the URL.
NOTE: You can use this service to send any file to the server.
then call that service like the following:
var files = [{ name: "xx", filename:"xx", filepath: "xx", filetype: "xx" }];
await sendFileToServer(files)
NOTE: each object must have name,filename,filepath,filetype
A couple of potential alternatives are available. Firstly, you could use the XHR polyfill:
http://facebook.github.io/react-native/docs/network.html
Secondly, just ask the question: how would I upload a file in Obj-C? Answer that and then you could just implement a native module to call it from JavaScript.
There's some further discussion on all of this on this Github issue.
Tom's answer didn't work for me. So I implemented a native FilePickerModule which helps me choose the file and then use the remobile's react-native-file-transfer package to upload it. FilePickerModule returns the path of the selected file (FileURL) which is used by react-native-file-transfer to upload it.
Here's the code:
var FileTransfer = require('#remobile/react-native-file-transfer');
var FilePickerModule = NativeModules.FilePickerModule;
var that = this;
var fileTransfer = new FileTransfer();
FilePickerModule.chooseFile()
.then(function(fileURL){
var options = {};
options.fileKey = 'file';
options.fileName = fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType = 'text/plain';
var headers = {
'X-XSRF-TOKEN':that.state.token
};
options.headers = headers;
var url = "Set the URL here" ;
fileTransfer.upload(fileURL, encodeURI(url),(result)=>
{
console.log(result);
}, (error)=>{
console.log(error);
}, options);
})
Upload Files : using expo-image-picker npm module. Here we can upload any files or images etc. The files in a device can be accessed using the launchImageLibrary method. Then access the media on that device.
import * as ImagePicker from "expo-image-picker";
const loadFile = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
aspect: [4, 3],
});
return <Button title="Pick an image from camera roll" onPress={loadFile} />
}
The above code used to access the files on a device.
Also, use the camera to capture the image/video to upload by using
launchCameraAsync with mediaTypeOptions to videos or photos.