我正在使用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);
};
错误错误:EISDIR:在此上下文中对目录的非法操作表示您将Multer的目标设置为目录,而该目录应该是目标文件的名称。
目标在Routes.js中的行cb(null, path.join(__dirname, 'uploads'));
中设置。如果你把这一行改成像cb(null, path.join(__dirname, 'myDirectory\\mySubdirectory\\', myFilename + '.jpg'))
这样的东西,那就行了。