Search code examples
node.jsreact-nativeuploadmulter

How to use Multer middleware to upload array of images


Im trying to use Multer to upload an array of images. At the client side i have a FormData called pictures.

pictures array, from react-native-image-picker:

const [pictures, setPictures] = useState([]);
const imagePickerCallBack = data => {
    const picturesData = [...pictures];
    const index = picturesData.length;
    const image = {
      image: data.uri,
      fileName: data.fileName,
      type: data.type,
      index: index,
    };

    picturesData.push(image);

    setPictures(picturesData);
    setLoad(false);
  };

Step 1 - Create formData with all images:

const data = new FormData();

pictures.forEach(pic => {
        data.append('pictures', {
          fileName: pic.fileName,
          uri: pic.image,
          type: pic.type,
        });
      });
const headers = {
    'Content-Type': 'multipart/form-data',
    'x-access-token': token,
  };

const diaryUpdatePost = await post(`diary/uploadPictures/${diary}`, body, {
    headers,
  });

Step 2 - Get the request at server side. Im setting up multer and routers:

const router = express.Router();
const multer = require('multer');

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, 'uploads/');
  },
  filename(req, file, cb) {
    cb(null, `${file.fieldname}-${Date.now()}`);
  },
});

const upload = multer({ storage, limits: { fieldSize: 25 * 1024 * 1024 } });

// Multer with the same FormData (client)
router.post('/uploadPictures/:name', upload.array('pictures'), diaryController.uploadDiaryPictures);

And finally my diaryController, where i need to get all files:

exports.uploadDiaryPictures = async (req, res) => {
  // Logging []. I cant access files from here
  console.log(`files ${req.files}...`);
};

I already tried to use express-fileupload, but req.files return undefined. Some ideia to help? Thx.


Solution

  • You need to give a count of files you expect to upload:

    upload.array('pictures', <number_of_pictures>)
    

    Or if it is allowed to be any number:

    upload.any('pictures')
    

    You should also add the file itself to your form data

    data.append('pictures', {
        name: pic.fileName,
        file: pic.image,
        type: pic.type,
    });