【问题标题】:How to Process Uploaded Image with Graphql Apollo with SharpJS in NodeJS?如何在 NodeJS 中使用 Graphql Apollo 和 SharpJS 处理上传的图像?
【发布时间】:2021-08-16 13:38:24
【问题描述】:

我有一个 graphql 突变,它从前端获取图像,然后在我的服务器上进行处理和优化。

但我不知道如何将图像传递给Sharp。

这是我的代码:

const Mutation = {
    createImage: async (_, { data }) => {
        const { file } = data
        const image = await file

        console.log(image)

        const sharpImage = sharp(image)
    }
}

我知道代码不起作用,sharp 抛出一个错误,指出输入无效。那么如何使用createReadStream 并创建sharp 的实例?

当我console.log(image) 时,我看到的是:

image {
  filename: 'image.png',
  mimetype: 'image/png',
  encoding: '7bit',
  createReadStream: [Function: createReadStream]
}

提前非常感谢!

【问题讨论】:

  • 流!= 缓冲区?
  • @xadm 感谢您的意见。我知道流不是缓冲区。我只是想提供一些可以使用的示例。我正在尝试了解如何使用createReadStream 并使用sharp 处理图像
  • 检查 args ... 文件是否已准备就绪(当然,如果正确通过)... console.log 图像或文件 ... stackoverflow.com/a/61452904/6124657
  • @xadm 当我将等待的文件结果传递给Sharp时,我仍然得到[Error: Input file is missing]。我将等待文件的console.log的结果添加到我的问题中
  • 它接缝你可以使用流...stackoverflow.com/a/61786860/6124657

标签: node.js graphql apollo-server sharp


【解决方案1】:

所以我想出了解决问题的方法。

首先,我发现我需要将scalar Upload 添加到typeDefs

然后,我需要像这样为Upload 添加解析器:

const { GraphQLUpload } = require('graphql-upload');

const server = new ApolloServer({
  resolvers: {
    Upload: GraphQLUpload,
  }
})

然后在我的解析器中,这是我必须做的:

// this is a utility function to promisify the stream and store the image in a buffer, which then is passed to sharp
const streamToString = (stream) => {
    const chunks = [];
    return new Promise((resolve, reject) => {
        stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
        stream.on('error', (err) => reject(err));
        stream.on('end', () => resolve(Buffer.concat(chunks)));
    })
}

const Mutation = {
    createImage: async (_, { data }) => {
        const { file } = data
        const { createReadStream } = await file

        const image = await streamToString(createReadStream())

        const sharpImage = sharp(image)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-04
    • 2019-04-04
    • 2018-01-28
    • 2020-01-30
    • 2018-08-01
    • 2020-02-22
    • 1970-01-01
    • 2020-02-08
    相关资源
    最近更新 更多