0
votes

How can I upload a file( pdf, docs etc) from React Native using expo to the server using node. I've seen many examples for images using the expo image-picker api but I've come across none that uses document-picker or filesystem apis from expo. The expo file system documentation was a little hard to interpret for a beginner like me.

3

3 Answers

1
votes

Thanks for the help. I was able to come up with a solution and I'll post it below so it can be of some use to whoever comes here in the future.

React Native

import React, { useState } from 'react';
import { Button, View } from 'react-native';
import * as DocumentPicker from 'expo-document-picker';
import * as FileSystem from 'expo-file-system';

const DocPicker = () => {
    const [ doc, setDoc ] = useState();
    const pickDocument = async () => {
        let result = await DocumentPicker.getDocumentAsync({ type: "*/*", copyToCacheDirectory: true }).then(response => {
            if (response.type == 'success') {          
              let { name, size, uri } = response;
              let nameParts = name.split('.');
              let fileType = nameParts[nameParts.length - 1];
              var fileToUpload = {
                name: name,
                size: size,
                uri: uri,
                type: "application/" + fileType
              };
              console.log(fileToUpload, '...............file')
              setDoc(fileToUpload);
            } 
          });
        // console.log(result);
        console.log("Doc: " + doc.uri);
    }

    const postDocument = () => {
        const url = "http://192.168.10.107:8000/upload";
        const fileUri = doc.uri;
        const formData = new FormData();
        formData.append('document', doc);
        const options = {
            method: 'POST',
            body: formData,
            headers: {
              Accept: 'application/json',
              'Content-Type': 'multipart/form-data',
            },
        };
        console.log(formData);

        fetch(url, options).catch((error) => console.log(error));
    }

    return (        
        <View>
            <Button title="Select Document" onPress={pickDocument} />
            <Button title="Upload" onPress={postDocument} />
        </View>
    )
};

export default DocPicker;

Node.js

const express = require('express')
const bodyParser = require('body-parser')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })
const app = express()
const fs = require('fs')
const http =  require('http')
const port = 8000


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req,res) => {
    res.json({
        success: true
    })
})


app.post('/', (req, res) => {
    console.log(req.body)
    res.status(200)
  })

app.post('/upload', upload.single('document'),(req , res) => {
  console.log(req.file, req.body)
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Cheers!!!

0
votes

Here is an example, which also uses multer and express on the backend: https://github.com/expo/examples/tree/master/with-formdata-image-upload

That said, I'd recommend using FileSystem.uploadAsync instead of fetch and the background sessionType in order to support uploads while the app is backgrounded on iOS.