【问题标题】:File uploads with typegraphql (Apollo Server)使用 typegraphql (Apollo Server) 上传文件
【发布时间】:2021-10-13 11:16:00
【问题描述】:

我想做什么

我正在尝试使用typegraphql(Apollo 服务器上的包装器)上传文件。我正在编写一个简单的解析器,它应该接收文件上传并将其写入服务器上的文件。

我的代码

我关注了这个tutorial

我已将一个非常小的问题演示上传到此github repo。 这是我接收上传文件的解析器

@Resolver()
export class ProfilePictureResolver {
  @Mutation(() => Boolean)
  async addProfilePicture(
    @Arg('picture', () => GraphQLUpload)
    upload: FileUpload
  ): Promise<boolean> {
    console.log('upload', upload);
    const { createReadStream, filename } = upload;
    return new Promise(async (resolve, reject) =>
      createReadStream()
        .pipe(createWriteStream(__dirname + `/../../../images/${filename}`))
        .on('finish', () => resolve(true))
        .on('close', () => resolve(true))
        .on('error', () => reject(false))
    );
  }
}

我的问题

当我运行这个解析器(使用教程中所示的邮递员)时,promise 永远不会解析。 createReadStream 不会发出关闭、错误或完成事件。图像文件确实已创建,但它是空的(0 字节)。

任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: javascript node.js typescript apollo-server typegraphql


    【解决方案1】:

    我用不同的方式做这个也许这可以帮助你我使用graphql-upload库上传图片

    在你的索引或服务器文件中,你需要有这个,在我的例子中,我是用快递做的,但是有一个阿波罗的设置

    import { graphqlUploadExpress } from 'graphql-upload'
    import { graphqlHTTP }  from 'express-graphql';
    
        App.use('/graphql', graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }), graphqlHTTP(async(req, res) => 
        ({
            schema: await buildSchema
            ({
                resolvers: 
                [
                    ProfilePictureResolver ,
                ],
    
            }),
    
    
        })));
    

    还有解析器

    @Resolver()
    export class ProfilePictureResolver 
    {
      @Mutation(() => Boolean)
      async addProfilePicture(
      @Arg('picture', () => GraphQLUpload)upload: FileUpload): Promise<boolean> 
      {
        return new Promise(async (resolve, reject) =>
          createReadStream()
            .pipe(createWriteStream(__dirname + `/../../../images/${filename}`))
            .on('finish', () => resolve(true))
            .on('close', () => resolve(true))
            .on('error', () => reject(false))
        );
      }
    }
    

    createReadStream 在你的文件夹中创建一个文件我认为最好直接上传到你的存储服务器但继续这个,邮递员有点难使用 whit graphql 你可以尝试使用Altair

    她可以看到Upload the file whit altair的选项

    您的 Graphql 查询应如下所示

    mutation ($Picture: Upload!)
    {
      
      addProfilePicture
      (
        upload: $Picture,
      )
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 2021-05-01
      • 2021-05-27
      • 2021-12-10
      • 2019-04-30
      • 2020-12-20
      • 2021-04-04
      • 2020-12-04
      • 2020-09-29
      相关资源
      最近更新 更多