将图像从节点上传到Cloudinary

时间:2018-11-22 09:04:15

标签: node.js cloudinary

我正在尝试将文件内容流式传输到Cloudinary中,并使用返回URL传递到我的数据库中

我已经成功实现了graphql-upload,可以将图像文件从客户端上传到服务器。我可以从服务器端检索流,文件名,mimetype和编码

在那之后,我无法将图像发送到Cloudinary。以下是我的代码...谢谢指教

谢谢

import cloudinary from 'cloudinary';

Mutation: {
        uploadPicture: async (_, { file }) => {
          // Works Ok
      const { stream, filename, mimetype, encoding } = await file;

      try {

        cloudinary.config({
          cloud_name: process.env.cloud_name,
          api_key: process.env.CLOUDINARY_API_KEY,
          api_secret: process.env.CLOUDINARY_API_SECRET
        });

// Below is the area where I am unsure
        var upload_stream = cloudinary.uploader.upload_stream(
          { tags: "sample" },
          function(err: any, image: any) {
            console.log();
            console.log("** Stream Upload");
            if (err) {
              console.warn(err);
            }
            console.log("* Same image, uploaded via stream");
            console.log("* " + image.public_id);
            console.log("* " + image.url);
          }
        );
        const file_reader = fs
          .createReadStream(stream)
          .pipe(upload_stream);


      } catch (error) {
        throw error;
      }
      return true;
    },

1 个答案:

答案 0 :(得分:0)

尝试将v2添加到通话中

var upload_stream= cloudinary.v2.uploader.upload_stream({tags: 'basic_sample'},function(err,image) {
  console.log('here');
  console.log("** Stream Upload");
  //if (err){ console.warn(err);}
  console.log("* Same image, uploaded via stream");
  console.log("* "+image.public_id);
  console.log("* "+image.url);
});
var file_reader = fs.createReadStream('picture.jpg').pipe(upload_stream);