I've been working with react native for one year now, and I really love it.
Today was the first time I had to upload files to our back-end server.
Normally when I encounter something I don't know my first instinct is to search for it in the official documentations unfortunately I couldn't find anything helpful.
Without using third party library:
Prepare file as form data:
If you picked a file using document picker,image picker or camera and you pass it down as file object.
const data = new FormData();
data.append('file', {
name: file.name,
type: file.type,
uri: Platform.OS === 'ios' ?
file.uri.replace('file://', '')
: file.uri,
});
Notice that on ios you need to prefix file path with 'file://' to be able to access files.
Upload the file to the server as Post request with proper headers:
- Using Axios :
await Axios.post("https://upload-service-url", data, {
headers: {
"Content-Type": "multipart/form-data",
},
});
- Using fetch :
await fetch("https://upload-service-url", {
method: "post",
body: data,
headers: {
"Content-Type": "multipart/form-data; ",
},
});
Using react-native-fs library:
Library repo
This nice library give you access to native files system so you can manipulate files and directories.
Why to use this library if I can do it without library?
I would say the main reason is to have the ability to show determinate progress indicator using the progress callback
import { uploadFiles, DocumentDirectoryPath } from "react-native-fs";
var files = [
{
name: "file",
filename: "file.jpg",
filepath: DocumentDirectoryPath + "/file.jpg",
filetype: "image/jpeg",
},
];
uploadFiles({
toUrl: "https://upload-service-url",
files: files,
method: "POST",
headers: {
Accept: "application/json",
},
//invoked when the uploading starts.
begin: () => {},
// You can use this callback to show a progress indicator.
progress: ({ totalBytesSent, totalBytesExpectedToSend }) => {},
});
Important note:
If you are using react native debugger to try inspecting network requests and you get errors from back-end service.
It is because currently the debugger does'nt suppot the formData as mentioned in there documentations under 'Limitations'
react-native-debugger
Top comments (0)