尝试将图像上传到Cloudinary时收到TypeError

时间:2019-05-30 13:13:42

标签: node.js express multer cloudinary

我一直试图将图像直接从表单上传到cloudinary。 每当我尝试上传图像时,都会收到以下错误消息:

/mnt/c/NodeApps/uploadFile/node_modules/multer-storage-cloudinary/lib/index.js:67
    var stream = _this.cloudinary.v2.uploader.upload_stream(params, cb);
                                         ^
    TypeError: Cannot read property 'uploader' of undefined
    at /mnt/c/NodeApps/uploadFile/node_modules/multer-storage-cloudinary/lib/index.js:67:42
    at end (/mnt/c/NodeApps/uploadFile/node_modules/run-parallel/index.js:18:15)
    at process._tickCallback (internal/process/next_tick.js:61:11)

我的表单:

<form action='upload' method="POST" enctype="multipart/form-data">
    <input type='text' name='caption' placeholder="Name the image">
    <input type="file" name="new_image">
    <button type='submit'>Submit</button>
</form>

来自app.js

var multer                  = require('multer');
var cloudinary              = require('cloudinary').v2;
var cloudinaryStorage       = require('multer-storage-cloudinary');
var bodyParser              = require('body-parser');

var app = express();

app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:true}));

Cloudinary配置:

cloudinary.config({
    cloud_name: process.env.cloud_name,
    api_key: process.env.API_KEY,
    api_secret: process.env.API_SECRET
});

var storage = cloudinaryStorage({
    cloudinary: cloudinary,
    folder: "demo",
    allowedFormats: ['jpg', 'png'],
});
var parser = multer({ storage: storage });

我的帖子路线:

app.post('/upload', parser.single('new_image'), (req, res) => {
    cloudinary.v2.uploader.upload(req.file.path, (err, result) => {
        if (err) { console.log('Error: ' + err); }
        image.url = result.secure_url;
        console.log(image.url);
    });
});

尝试解决此错误完全让我感到困惑,对我要去哪里的任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为您忽略了一个小错误-在此处需要时,您已经遍历了SDK的v2对象:

var cloudinary = require('cloudinary').v2;

所以,在这段代码中:

cloudinary.v2.uploader.upload(req.file.path, (err, result) => {
    ...
}

您实际上是在呼叫cloudinary.v2.v2.uploader而不是cloudinary.v2.uploader。因此,由于cloudinary.v2.v2未定义,导致无法调用上载方法的错误。在您的要求行中或致电上传者的位置删除.v2


一个单独的问题是,根据代码,您似乎将要双重上传图像。由于您已将multer配置为使用Cloudinary作为存储目标,因此将其用作中间件应该意味着它本身就可以上传到Cloudinary,因此,当您调用.uploader.upload()时,实际上是第二次上传。我相信这将是更正确的代码:

app.post('/upload', parser.single('new_image'), (req, res) => {
    // Since multer is the middleware & set to single, req.file should be an object with the results from cloudinary
    let image = {};
    image.url = req.file.secure_url;
    console.log(image.url);
});

我发现一些参考资料很有帮助: