1

我正在使用MulterSharp来存储作为 HTML 表单的一部分上传的图像。我想在将图像存储在磁盘上之前调整它们的大小并对其进行转换,并找到了关于如何做到这一点的线程。

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

错误:EISDIR:对目录的非法操作,打开 'C:\...\uploads'

下面是我的代码:

路线.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);
};
4

1 回答 1

0

错误Error: EISDIR:在此上下文中对目录进行非法操作表明您将 Multer 的目标设置为一个目录,而它应该是目标文件的名称。

cb(null, path.join(__dirname, 'uploads'));目的地在Routes.js的行中设置。如果您将此行更改为类似cb(null, path.join(__dirname, 'myDirectory\\mySubdirectory\\', myFilename + '.jpg'))的内容,它将起作用。

于 2018-02-16T21:59:05.853 回答