自定义Multer存储 - 使用锋利时的非法操作



我正在使用multer和尖锐的贴合图像作为HTML形式的一部分上传。我想在将图像存储在磁盘上之前调整并更改图像,并找到有关如何执行此操作的线程。

我以为我已经正确设置了所有内容,但是当我尝试上传图像时,我会得到:

错误: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'))之类的东西,它将起作用。

最新更新