【发布时间】:2018-07-27 20:18:49
【问题描述】:
我正在使用 Multer 和 Sharp 来存储作为 HTML 表单的一部分上传的图像。我想在将图像存储在磁盘上之前调整它们的大小和转换它们并找到this 线程关于如何做到这一点。
我以为我已经正确设置了一切,但是当我尝试上传图片时,我得到:
错误:EISDIR:对目录的非法操作,打开 'C:\...\uploads'
下面是我的代码:
Routes.js:
var multer = require('multer');
var customStorage = require(path.join(__dirname, 'customStorage.js'));
var upload = multer({
storage: new customStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, 'uploads'));
},
filename: function (req, file, cb) {
cb(null, Date.now());
}
}),
limits: { fileSize: 5000000 }
});
...
app.use('/upload', upload.single('file'), (req, res) => { ... });
customStorage.js:
var fs = require('fs');
var sharp = require('sharp');
function getDestination (req, file, cb) {
cb(null, '/dev/null'); // >Implying I use loonix
};
function customStorage (opts) {
this.getDestination = (opts.destination || getDestination);
};
customStorage.prototype._handleFile = function _handleFile(req, file, cb) {
this.getDestination(req, file, function (err, path) {
if (err) return cb(err);
var outStream = fs.createWriteStream(path);
var transform = sharp().resize(200, 200).background('white').embed().jpeg();
file.stream.pipe(transform).pipe(outStream);
outStream.on('error', cb);
outStream.on('finish', function () {
cb(null, {
path: path,
size: outStream.bytesWritten
});
});
});
};
customStorage.prototype._removeFile = function _removeFile(req, file, cb) {
fs.unlink(file.path, cb);
};
module.exports = function (opts) {
return new customStorage(opts);
};
【问题讨论】:
-
您收到的错误中是否还有更多信息,例如抛出错误的特定行?
-
很遗憾,没有。
-
你能在 Routes.js 中的
destination函数中控制台记录path.join(__dirname, 'uploads')吗? -
customStorage.js:i.imgur.com/EDO7Wgm.pngRoutes.js:
Path: C:\Users\lolechi\Desktop\nosos\public\rooms我撒了一点谎,说图片上传到uploads,但实际上是上传到public\rooms。跨度> -
在你运行代码之前这个目录是否已经存在?如果是这样,请尝试将路径名更改为不存在的目录(可能是
C:\Users\lolechi\Desktop\nosos\public\uploads)并查看它是否有效。我认为 Multer 要求它在运行时创建一个新目录。