使用Nodejs API的图像上传问题

hrysbysz  于 2023-04-20  发布在  Node.js
关注(0)|答案(1)|浏览(137)

我是Nodejs和express的新手,现在我正在尝试上传图像,但我面临两个问题

1) Image format/extension is wrong , showing "file" instead of original image (.jpg or png or other extension should be added) 
2) If we pass "file","image" or other parameters then 2 or more files uploading,There should be one parameter "image"

下面是我的当前代码

var upload = multer({ dest: 'upload/'});
var fs = require('fs');
var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});

 var upload = multer({ storage: storage }).any('userPhoto');
 const uploadavatar = function (req, res) {
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file." + err);
        }
        res.end("File is uploaded");
    });
};

ubbxdtey

ubbxdtey1#

尝试使用下面的文件名函数代码

filename: function (req, file, callback) {
        const originalname = file.originalname;
        const fileExt = originalname.split(".").pop();
        const excatName = originalname.split(".").slice(0, -1).join(".");
        callback(null, excatName + "-" + Date.now().toString() + "." + fileExt);
      },

相关问题