【问题标题】:upload photo from file or postman by image address in my drive通过我驱动器中的图像地址从文件或邮递员上传照片
【发布时间】:2021-05-14 18:32:07
【问题描述】:

我有这样的架构:

const Person = new mongoose.Schema({
  username: {
    type: String,
    required: [true, "Name is a required field"],
    unique: [true, "Another Person with the same name already exists"],
    trim: true
  },
  friends: [
    {
      name: {
        type: String,
        required: [true, "Every friend must have a name"],
        unique: [true, "Another friend with the same name already exists"],
        trim: true
      },
     photo: String,
     favoriteFood: String
    }
  ],
  createdAt: {
    type: Date,
    default: Date.now()
  }
});

我想为每个朋友添加一张图片,但我想通过在请求中在我的硬盘驱动器中添加图片地址来从邮递员或播种文件之类的东西上传照片。因为我有几个朋友,我必须为每个朋友制作每张照片。我想在邮递员正文或文件中做这样的事情作为播种机来填充数据库或向其中添加数据。

{
"username": "aUsername",
"friends": [
   {
     "name": "friend1",
     "photo": "./home/user/photos/photo1.jpg",
     "favoriteFood": "Pizza"
   },
   {
     "name": "friend2",
     "photo": "./home/user/photos/photo2.jpg",
     "favoriteFood": "Sushi"
   },   
   {
     "name": "friend3",
     "photo": "./home/user/photos/photo3.jpg",
     "favoriteFood": "Hamburger"
   }
    ]
}

如何在后端创建此功能?

谢谢。

【问题讨论】:

    标签: javascript node.js postman backend


    【解决方案1】:
    const multer = require('multer');
    
    const storage = multer.diskStorage({
      destination: function(req, file, callback) {
        callback(null, '/src/my-images');
      },
      filename: function (req, file, callback) {
        callback(null, file.fieldname);
      }
    });
    
    app.post('/', upload.single('file'), (req, res) => {
      if (!req.file) {
        console.log("No file received");
        return res.send({
          success: false
        });
    
      } else {
        console.log('file received');
        return res.send({
          success: true
        })
      }
    });
    

    【讨论】:

    • 谢谢你,但如果你能解释一下就好了。
    猜你喜欢
    • 1970-01-01
    • 2022-08-20
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2021-10-13
    • 2012-10-09
    相关资源
    最近更新 更多