【问题标题】:Custom Multer storage - Illegal operation when using Sharp自定义 Multer 存储 - 使用 Sharp 时的非法操作
【发布时间】:2018-07-27 20:18:49
【问题描述】:

我正在使用 MulterSharp 来存储作为 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 要求它在运行时创建一个新目录。

标签: node.js multer sharp


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    相关资源
    最近更新 更多