使用Cloudinary的Apollo上载客户端

时间:2018-11-17 06:23:57

标签: node.js apollo cloudinary express-graphql

我正在尝试使用apollo-upload-client,graphql和cloudinary上传图像,

目标:要成功将图片上传到cloudinary,请获取cloudinary网址并插入数据库中

当前:未收到任何错误消息,但看不到文件上传到cloudinary

帮助:下面的代码正确吗?任何人都已在其代码中成功实现了apollo-client-upload,graphql和cloudinary解决方案?如何从cloudinary获取响应URL,我可以将其插入到数据库中

到目前为止,我已经测试过上传到我们自己的本地服务器,并且代码运行正常。我已经隔离,错误可能来自下面的部分

预先感谢

export const cloudinaryUpload = async ({ stream }: any): Promise<string> => {
  console.log("stream upload gql ", stream);
  cloudinary.config({
    cloud_name: process.env.cloud_name,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET
  });

  cloudinary.uploader
    .upload_stream({ resource_type: "raw" }, function(error: any, result: any) {
      console.log("error ", error);
      console.log("result ", result);
    })
    .end(stream.buffer);

  return `Test`;
};



export const processUpload = async (upload: any) => {

  const { stream } = await upload;

  const { id } = await storeUpload({ stream });
  return `id`;

2 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,试图弄清楚如何将文件上传到cloudinary,并在这里和Cloudinary的支持论坛中遇到了这个问题。

如果其他任何人遇到困难,这里是解决方法:https://support.cloudinary.com/hc/en-us/community/posts/360031762832-graphql-upload-with-cloudinary

答案 1 :(得分:0)

这对我有用:

const cloudinary = require('cloudinary').v2;
cloudinary.config({
  cloud_name: process.env.CLOUDINARY_CLOUDNAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRECT,
});

const imageUpload = async (imageFile) => {
  try {
    const { createReadStream } = await imageFile;
    const stream = createReadStream();
    const cloudinaryResponse = await cloudinary.uploader.upload(stream.path, { folder: 
'my-folder' });
    return cloudinaryResponse.eager[0].secure_url;
  } catch (error) {
    throw new Error('There was a problem uploading your image. Please try again.');
  }
};