簡體   English   中英

使用 React Native 和 Nodejs Express Multer 上傳圖片

[英]Image upload with React Native and Nodejs Express Multer

我有一個 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 的帖子請求:

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

最近我遇到了同樣的問題,因為有一個未解決的問題,請參閱此處的 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 中一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM