首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么当我用apollo-server上传文件时,文件被上传了,但是文件是0kb的?

为什么当我用apollo-server上传文件时,文件被上传了,但是文件是0kb的?
EN

Stack Overflow用户
提问于 2021-01-27 17:46:03
回答 1查看 177关注 0票数 0
代码语言:javascript
复制
const { ApolloServer, gql } = require('apollo-server');
const path = require('path');
const fs = require('fs');

const typeDefs = gql`
  type File {
    url: String!
  }

  type Query {
    hello: String!
  }

  type Mutation {
    fileUpload(file: Upload!): File!
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
  Mutation: {
    fileUpload: async (_, { file }) => {
      const { createReadStream, filename, mimetype, encoding } = await file;
      const stream = createReadStream();
      const pathName = path.join(__dirname, `/public/images/${filename}`);
      await stream.pipe(fs.createWriteStream(pathName));

      return {
        url: `http://localhost:4000/images/${filename}`,
      };
    },
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen().then(({ url }) => {
  console.log(` Server ready at ${url}`);
});

然后,当我上传文件时,它被上传了,但文件是0kb

like this

EN

回答 1

Stack Overflow用户

发布于 2021-01-31 09:20:00

发生的情况是,解析器在文件上传之前返回,导致服务器在客户端完成上传之前做出响应。您需要在解析器中暂停并等待文件上传流事件。

下面是一个示例:

https://github.com/jaydenseric/apollo-upload-examples/blob/c456f86b58ead10ea45137628f0a98951f63e239/api/server.js#L40-L41

在您的案例中:

代码语言:javascript
复制
const resolvers = {
  Query: {
    hello: () => "Hello world!",
  },
  Mutation: {
    fileUpload: async (_, { file }) => {
      const { createReadStream, filename } = await file;
      const stream = createReadStream();
      const path = path.join(__dirname, `/public/images/${filename}`);

      // Store the file in the filesystem.
      await new Promise((resolve, reject) => {
        // Create a stream to which the upload will be written.
        const writeStream = createWriteStream(path);

        // When the upload is fully written, resolve the promise.
        writeStream.on("finish", resolve);

        // If there's an error writing the file, remove the partially written
        // file and reject the promise.
        writeStream.on("error", (error) => {
          unlink(path, () => {
            reject(error);
          });
        });

        // In Node.js <= v13, errors are not automatically propagated between
        // piped streams. If there is an error receiving the upload, destroy the
        // write stream with the corresponding error.
        stream.on("error", (error) => writeStream.destroy(error));

        // Pipe the upload into the write stream.
        stream.pipe(writeStream);
      });

      return {
        url: `http://localhost:4000/images/${filename}`,
      };
    },
  },
};

请注意,使用这样的文件名来存储上传的文件可能不是一个好主意,因为以后使用相同文件名的上传将覆盖以前的文件。我真的不确定如果两个客户端同时上传两个同名的文件会发生什么。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65916544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档