【问题标题】:Image upload with React Native and Nodejs Express Multer使用 React Native 和 Nodejs Express Multer 上传图片
【发布时间】:2018-12-16 07:53:07
【问题描述】:

我有一个在本地运行的带有 Express 服务器的 Nodejs,允许我上传图像,我在 Postman 上没有问题,但是当我尝试从 React Native 上传时,服务器获取请求数据,包括图像,但不要上传到服务器!我在这里做错了什么,请看一下!

这是我的 multer 配置:

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './server/uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, new Date().toISOString() + file.originalname);
  }
})

const fileFilter = (req, file, cb) => {
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'image') {
    cb(null, true);
  } else {
    cb(null, false);
  }
}

const upload = multer({ 
  storage: storage, 
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter,
});

这是我的路线调用:

route.post('/products', upload.single('image'), userAuthenticate, ProductController.createProduct);

这是我的控制器:

export const createProduct = async (req, res) => {
  try {
    console.log(req);

    const { serial, name, description, cate_id, quantity, origin_price, sell_price, attributes } = req.body;
    const newProduct = new Product({ serial, name, description, cate_id, quantity, origin_price, sell_price, attributes });

    newProduct._creator = req.user._id;

    // upload image  
    console.log(req.file);
    newProduct.image = fs.readFileSync(req.file.path);

    let product = await newProduct.save();
    let user = req.user;
    user._products.push(product);
    await user.save();
    return res.status(201).json({ product });
  } catch (e) {
    console.log(e.message);
    return res.status(e.status || 404).json({ err: true, message: e.message });
  }
}

这是我来自 react native 的发帖请求:

const data = new FormData();
    data.append('serial', serial);
    data.append('name', name);
    data.append('description', description);
    data.append('sell_price', [{ 'value': sell_price }]);
    data.append('origin_price', origin_price);
    data.append('quantity', quantity);
    data.append('cate_id', cate_id);
    data.append('attr', attr);
    data.append('image', {
      uri: image.uri,
      type: image.type,
      name: image.name
    });

    let product = await axios({
      method: 'POST',
      url: 'http://localhost:3000/api/products',
      data: data,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data', 
        'x-auth': token, 
      }
    })

这是我在产品模型中的图像字段:

image: {
    type: Buffer
  },

【问题讨论】:

    标签: node.js express react-native image-uploading multer


    【解决方案1】:

    最近我遇到了同样的问题,因为在 react native 上有一个未解决的问题See here

    但我使用rn-fetch-blob找到了一个不错的解决方案

    正如您在文档中看到的,您可以实现以下内容:

    upload = async () => {
        let ret = await RNFetchBlob.fetch(
          'POST',
          'http://localhost:3000/api/products',
          {
            'Content-Type': 'multipart/form-data',
            'x-auth': token, 
          },
          [
            {
              name: 'image',
              filename: Date.now() + '.png',
              type: 'image/png',
              data: RNFetchBlob.wrap(image.uri),
            },
          ],
        );
        return ret;
      };
    

    如您所见,有一个数组,您可以在其中添加要上传的对象,就像在 FormData 中一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-14
      • 2021-10-17
      • 2018-11-23
      • 2016-09-14
      • 2017-03-03
      • 1970-01-01
      • 2018-09-17
      • 2021-07-05
      相关资源
      最近更新 更多