错误:ENOENT:没有这样的文件或目录,在上传图像时打开错误(本机)目录

时间:2018-04-11 06:37:38

标签: node.js multer

我想使用multer上传图片,但是当我更改 app.js 时,我尝试了很多解决方案,但我没有工作:(

var multer = require('multer');
var path = require('path');
var id_photo = uuidv1();

global.appRoot = __dirname;

var storage = multer.diskStorage({

destination: function(req, file, callback) {
    callback(null, './uploads')
},
filename: function(req, file, callback) {
    callback(null, file.fieldname + '-' + id_photo + path.extname(file.originalname));
}
})

var upload = multer({
storage: storage,
fileFilter: function(req, file, callback) {
    var ext = path.extname(file.originalname)
    if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
        req.fileValidationError = "Only Image Allowed";
        return callback(null, false, req.fileValidationError)
    }
    callback(null, true)
}
}).any();

app.use(upload);
connection.init();

var multer = require('multer');
var path = require('path');

global.appRoot = __dirname;

var storage = multer.diskStorage({

destination: function(req, file, callback) {
    callback(null, './uploads')
},
filename: function(req, file, callback) {
    var id_photo = new Date();
    var dd = id_photo.getDate();
    var mm = id_photo.getMonth() + 1; //January is 0!
    var yyyy = id_photo.getFullYear();
    var h = id_photo.getHours();
    var i = id_photo.getMinutes();
    var s = id_photo.getSeconds();
    if (dd < 10) {
        dd = '0' + dd
    }

    if (mm < 10) {
        mm = '0' + mm
    }

    if (h < 10) {
        h = '0' + h
    }

    if (i < 10) {
        i = '0' + i
    }

    if (s < 10) {
        s = '0' + s
    }
    id_photo = mm + '-' + dd + '-' + yyyy + '-' + h + ':' + i + ':' + s;
    callback(null, id_photo + "*-" + file.originalname);

}
})

var upload = multer({
storage: storage,
}).any();

app.use(upload);
connection.init();

我收到这样的错误

错误:

  

ENOENT:没有这样的文件或目录,打开   'C:\的NodeJS \的NodeJS-WMC \上传\ 04-11-2018-13:20:09 * -8.jpg'       在错误(本机)

虽然文件上传已经存在,但当我使用app.js时,第一次运行顺利。我的代码有什么问题?

请帮帮我......谢谢你:)。

1 个答案:

答案 0 :(得分:1)

问题是您在路径中使用保留字符。根据{{​​3}},在Windows上保留以下符号:

< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)

如果您将路径格式更改为:

,它应该可以正常工作
id_photo = mm + '-' + dd + '-' + yyyy + '-' + h + '_' + i + '_' + s;
callback(null, id_photo + "-" + file.originalname);