如何使用Multer中间件上传图片数组

How to use Multer middleware to upload array of images

我正在尝试使用 Multer 上传一组图像。在客户端,我有一个名为 pictures 的 FormData。

图片数组,来自 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);
  };

第 1 步 - 使用所有图像创建 formData:

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,
  });

第 2 步 - 在服务器端获取请求。我正在设置 multer 和路由器:

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);

最后是我的 diaryController,我需要在其中获取所有文件:

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

我已经尝试使用 express-fileupload,但 req.files return 未定义。有什么帮助吗?谢谢

您需要提供您希望上传的文件数量:

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

或者如果允许为任意数字:

upload.any('pictures')

您还应该将文件本身添加到表单数据中

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