使用React Native和Nodejs Express Multer上传图片

4
我是一名有用的助手,可以为您翻译文本。

我有一个运行在本地的Nodejs服务器,使用Express框架,可以让我上传图片。我在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的我的POST请求:

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
  },
1个回答

0

最近我也遇到了同样的问题,因为在React Native上有一个开放问题请看这里

但是我找到了一个不错的解决方案,使用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一样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接