用Multer进行React-native-image-crop-picker上传

时间:2019-12-24 23:06:42

标签: node.js react-native multer

我正在使用react-native-image-crop-picker尝试将照片上传到我的Node.js后端。我已经呆了几个小时了,但是不知何故,在我通过Multer传递数据的路线中,req.files是否为空?另外,当我控制台登录日志req.body时,我的图像都是unicode,怎么回事?

本机图像选择器代码:

pickSingleListingImages = () => {
    ImagePicker.openPicker({
      multiple: true,
      width: 300,
      height: 400,
      cropping: true
    }).then(image => {
      console.log(image);
      this.props.handleImages(image); // sends image to state
    });
  };

提交数据:

if (!hasError) {
      let assetData = {...values};
      let formData = new FormData();
      await images.forEach((image, index) => formData.append("images[]", {
            filename: image.filename,
            type: image.mime,
            uri: Platform.OS === 'android' ? image.path : image.path.replace('file://', '')
      }));
      await delete assetData.images;
      formData.append("assetData", JSON.stringify(assetData));
      await this.props.addListing(formData); // Redux action to send data to backend
    };

添加列表操作:

const addListing = (values) => async dispatch => {
  await console.log("AssetData: ", values);
  const headers = { "Content-Type": "multipart/form-data" };
  await axios.post(getUrl("/api/v2/listings/create"), values, { headers });
}

后端:

import express from "express";
import Multer from 'multer';
import fs from 'fs';

const imageSizeLimit = 50 * 1000 * 1000;
const router = express.Router();
const upload = Multer({ limits: { fieldSize: imageSizeLimit  }, dest: 'uploads/' });


router.post("/create", upload.array("images[]", 15), (req, res, next) => {
  console.log('Upload files:=> ', req.files);
  console.log('Request body:=> ', req.body);
});

export default router;

结果:

// req.files
Upload Files:=> []

// req.body
[images]: [
 ...`K�W�\u0019;�s����^"�\u0000��\u000f��A^��6�\u0000�j���\u001a_���_�\u001e �\u0019��\u0000��\u001d�\u0000�r��g�F? +
],
  assetData: '{...}'
}

0 个答案:

没有答案