How to upload JavaScript File object to Cloudinary using node js api?

余生长醉 提交于 2020-02-04 04:41:22

问题


I need to upload a file to image server and i choose to go with cloudinary from my node js api. i installed the npm package for cloudinary and used the code as per their api documentation

here is my function which is making a http request call to upload image.

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

function uploadProfilePic(req, res, next) {
   let file = (req && req.files.file) ? req.files.file : ''; // File object
   cloudinary.uploader.upload(file, function (error, result) {
      if (!error && result.url) {
         req.body.imageURL = result.url;
         next();
      }
      else {
         req.body.imageURL = '';
         next();
      }
   }).end(file.data);
}

Getting error "file.match is not a function".

how to upload image using file object on cloudinary?


回答1:


Answering your question

How to upload image using file object on cloudinary?

In order to upload File object to cloudinary, you can use upload_stream method instead of upload. check documentation here.

Corrected your code:

var cloudinary = require('cloudinary').v2;
function uploadProfilePic(req, res, next) {
   let file = (req && req.files.file) ? req.files.file : '';
   cloudinary.uploader.upload_stream({ resource_type: 'raw' }, function (error, result) {
      if (!error && result.url) {
         req.body.imageURL = result.url;
         next();
      }
      else {
         req.body.imageURL = '';
         next();
      }
   }).end(file.data);
}


来源:https://stackoverflow.com/questions/56823532/how-to-upload-javascript-file-object-to-cloudinary-using-node-js-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!