【问题标题】:Upload the file (image) on Nodejs server using mongoose, with its original name使用 mongoose 在 Nodejs 服务器上上传文件(图像),并使用其原始名称
【发布时间】:2020-07-12 18:46:49
【问题描述】:

我正在使用 nodeJS 和 express 上传图像文件,目前,图像以随机文件名保存,没有特定文件类型。我想用扩展名保存文件名,以便我也可以显示它,因为当前在数据库中的文件名保存为原始文件,但在上传文件夹中,它分配了一个随机名称(字符串),当我获取它时我不知道如何显示它,因为它没有任何文件类型/扩展名,即.png/JPEG。

//Schema

const AddProductSchema = new Schema({

  productCode: String,
  productTitle: String,
  productImage: String

//defined express, mongoose, multer and upload const for the directory
const upload = multer({
  dest: __dirname + '/uploads/images'
});

//post method
app.post("/addProductToDB", upload.single("productImage"), function(req, res) {

// to get the detail filled on add product form
  const addproduct = new AddProduct({
    productCode: req.body.productCode,
    productTitle: req.body.productTitle,
    productImage: req.file.originalname

  });

  addproduct.save();
  res.redirect("/products");

});

【问题讨论】:

  • 管理使用 fs.rename 对其进行排序。我用文件名保存了文件,然后使用 fs.rename 将其替换为原始名称。 // fs.rename( __dirname + '/uploads/images/'+req.file.filename, __dirname + '/uploads/images/'+req.file.originalname, (err)=>{ if (err) { console .log(err); }else{ console.log("重命名完成"); }

标签: express mongoose multer


【解决方案1】:

如果要显示图像productImage: Buffer,则应将productImage保存为缓冲区类型
有一个名为 sharp 的软件包,它可以帮助您在保存到名为 sharp https://www.npmjs.com/package/sharp 的数据库之前自定义图像文件
如果你想在保存之前有 png 文件类型,你可以使用下面的代码

  const buffer = await sharp(req.file.buffer)
      .png()
      .toBuffer();

那么你只需要将缓冲区保存到你的productImage: buffer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多