【问题标题】:How to store image using nodejs,express,mongodb and react如何使用 nodejs、express、mongodb 存储图像并做出反应
【发布时间】:2019-10-24 17:28:59
【问题描述】:

我正在尝试使用 node 和 mongodb 存储图像。我在前端使用 react。我尝试使用 multer 但它给出错误说“TypeError:路径必须是字符串或缓冲区”。还有其他方法吗使用node和mongodb存储图片

 //server.js

 const multer = require("multer");

 const storage = multer.diskStorage({
 destination: function (req, res, cb) {
         cb(null, 'uploads/')
      }
 });

 const upload = multer({
     storage: storage
 });

 router.route('/imageCard/add').post(upload.single('file'), function                     (req, res) 
 {
     let imageDetails=new ImageCard();
     imageDetails.name=req.body.name;
     imageDetails.imgSource= fs.readFileSync(req.body.imgSource);
     imageDetails.price=req.body.price;
     imageDetails.size=req.body.size;
     imageDetails.save().then(details=>
      {
          res.status(200).json('Added');
      }).catch(err=>{
     result.status(400).send('Failed to Add');
     })

 });

 //(model )
 import mongoose from 'mongoose';
 const Schema = mongoose.Schema;

 let imageCard=new Schema({

     name:{
         type:String
     },
     imgSource:{

         type:Buffer
     },
     size:{
         type:String
     },
     price:{
         type:String
     }
 });

 export default mongoose.model('ImageCard', imageCard);

 //react file
 onChange(e) {   
    this.state.file = e.target.files[0];  
 }

 onsubmit() {
    console.log('on submit');
    const newDoc = {
        name: document.getElementById('name').value,
        price: document.getElementById('price').value,
        size: document.getElementById('size').value,

        imgSource:this.state.file
    }
    console.log(newDoc.imgSource);
              axios.post(`http://localhost:4000/imageCard/add`,newDoc).then(res=>{
        console.log(res.data);
    }).catch(err=>{
        console.log(err);
    });

}

如果我使用下面的代码,则会出现此错误:TypeError: Cannot read property 'path' of undefined

imageDetails.imgSource= fs.readFileSync(req.file.path);

我没有收到 server.js 文件中的 imgSource 值,它显示空值。

【问题讨论】:

    标签: node.js mongodb express react-native


    【解决方案1】:

    几天前我遇到了同样的问题。 最后我通过这样做来实现它:

        const multer  = require('multer');
    const path = require('path');
    
    
    const upload = multer({
        storage: multer.diskStorage({
            destination: (req, file, callback) => {
                try {
                    let path = "What ever your path is";
                    fs.mkdirsSync(path);
                    callback(null, path);
                }catch (e) {
                    callback(jsonError(e),null)
                }
            },
            filename: (req, file, callback) => {
                //original name is the uploaded file's name with ext
                callback(null, mongoose.Types.ObjectId()+path.extname(file.originalname));
            }
        })
    });
    

    然后在您的路线中制作您的 uoload.whatever。 请注意,一旦 multer 工作,您将拥有一个新的 req.file 或 req.files,其中包含名称、大小等

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 2020-11-21
      • 2021-10-27
      • 2015-06-29
      相关资源
      最近更新 更多