node.js - Multer 返回空响应

标签 node.js multer

我正在上传图像,但当我尝试实现一个功能时,我可以更改文件名以包含存储后的日期。

使用下面的代码,我将得到一个空对象,但仍然是一条成功的消息。 但是,如果我取消代码中的注释,它将起作用,但不会包含日期。

const express = require("express");
const multer = require("multer");
const app = express();

const fileFilter = function(req, file, cb){
    const allowedTypes = ["image/jpeg","image/png", "image/gif"];

    if(!allowedTypes.includes(file.mimetype)) {
        const error = new Error("wrong file type");
        error.code = "LIMIT_FILE_TYPES";
        return cb(error, false);
    }
    cb(null, true);
}
const storage = multer.diskStorage({
    destination:function(req, file, cb){
        cb(null, './uploads/')
    },
    filename:function(req, file, cb){
        cb(null, file + '-' + Date.now())
    }
});

const MAX_SIZE = 200000
const upload = multer({
    // dest: './uploads/', If I un-comment this line it will upload the image but will not change file name will still be random hash numbers
    fileFilter,
    storage:storage,
    limits:{
        fileSize: MAX_SIZE
    }
});

app.post('/upload', upload.single('file'), (req, res) => {
    res.json({file:req.file});
});

app.use(function(err, req, res, next) {
    if(err.code === "LIMIT_FILE_TYPES") {
        res.status(422).json({error:"Only Images are Allowed"});
        return;
    }
    if (err.code ==="LIMIT_FILE_SIZE"){
        res.status(422).json({error:`Size is to Large, Max size is ${MAX_SIZE/ 
  1000}KB`});
        return;
    }
});

app.listen(3344, () => console.log("running local on 3344"));

最佳答案

它返回未定义,因为您正在创建一个组合文件对象 + '-' + Date.now() 的字符串,因此更改此行:

cb(null, file + '-' + Date.now())

对于这个:

cb(null, file.fieldname + '-' + Date.now())

它应该可以完成这项工作。

关于node.js - Multer 返回空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54115957/

相关文章:

html - 如何解耦实时游戏架构

node.js - 如何在不使用 multer 和 node js 检查文件扩展名的情况下确定文件的真实类型

javascript - 如何使用 Multer 磁盘存储选项(NodeJs)读取存储的文件?

javascript - 在nodejs中强制在一段时间后关闭连接

node.js - 如何在 vs-code 中调试安装在 bot (botpress) 中的 botpress 模块?

javascript - Electron 存在而不会发出 render-process-gone 事件

ios - 从 AWS ACM 证书生成 .pem

node.js - express multer 无法读取未定义的属性 'profileimage'

Node.js -expressjs -multer req.files 输出为空

javascript - 使用 Multer 更改上传文件的目的地