【问题标题】:Node.js Multer FilenameNode.js Multer 文件名
【发布时间】:2018-07-03 20:17:29
【问题描述】:

我想通过输入值而不是字段名来自定义我的应用程序的文件名。
换句话说,我想将 file.filename 更改为 req.body.my_field 之类的东西,my_field 是输入的名称。
最后,我想要这样的东西:

"filename": "value_of_my_field-1530606094020.jpg",  
"path": "uploads\\value_of_my_field-1530606094020.jpg",  

注意到 my_field 的值出现在我的控制台上。
我需要一些帮助才能做到这一点。
这是我的代码:

var express = require('express')
var multer  = require('multer')
const path = require('path')

// Init app
var app = express()
const port= 3000

// Set storage engine
const storage = multer.diskStorage({
    destination: './uploads/',
    filename: function(req, file, cb){
        cb(null, file.fieldname + '-' + Date.now() +     path.extname(file.originalname));
    }
});

// Init upload
const upload = multer({
    storage: storage,
    limits:{fileSize:1000000},
});


app.post('/upload', upload.single('myImage'), function (req, res, next) {
    if(req.file == undefined){
        res.json({'Error': 'No File Selected!'});
    } else {
        res.json(req.file);
        console.log(req.body.my_field);
    }
})

app.listen(port, () => console.log('server started on port '+ port));

提前致谢

【问题讨论】:

    标签: node.js express filenames multer


    【解决方案1】:

    我不太确定您的问题是什么,因为您的代码当前似乎正在执行您希望它执行的操作(使用时间戳保存文件)。如果您想摆脱 req.body.my_field 的日志记录,请删除 console.log(req.body.my_field);

    【讨论】:

    • 这一行只验证 req.body.my_field 的内容。我只想要我的文件名上的这个值
    【解决方案2】:

    您应该能够在文件名函数中访问req 对象。所以你可以做这样的事情 -

    // Set storage engine
    const storage = multer.diskStorage({
        destination: './uploads/',
        filename: function(req, file, cb){
            cb(null, req.body.my_field + '-' + Date.now() +     path.extname(file.originalname));
        }
    });
    

    【讨论】:

    • 我尝试这样做,但结果未定义。 “文件名”:“undefined-1530620975355.jpg”,“路径”:“上传\\undefined-1530620975355.jpg”,
    • 你可以console.log(req.body) 看看你得到了什么吗?
    • 当我把它放在 app.post 中时,我在控制台 {my_field: 'value_of_field'} 上得到了这个结果。但是当我把它放在文件名函数中时,我得到了这个 {}
    猜你喜欢
    • 2016-05-22
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2017-12-03
    • 2020-06-19
    • 1970-01-01
    相关资源
    最近更新 更多