首页 > 解决方案 > 当我尝试将其发送到服务器时,graphql-upload 数据不起作用

问题描述

当使用 graphql-upload 然后我尝试将返回数据发送到烧瓶 python 服务器时,数据总是以正文而不是文件结束。content-type: multipart/form-data boundary etc....当我使用下面的 graphql 连接器时,标题会自动设置为成功。

我基于这个例子https://github.com/jaydenseric/apollo-upload-examples/blob/master/api/resolvers.mjs下面的很多内容

async fileUpload(page, id, file) {
  const { filename, mimetype, createReadStream } = await file;
  const stream = await createReadStream();

  const form = new FormData();
  form.append('file', JSON.stringify({
    filename, mimetype, stream
  }));

  // form.append('file', stream)); // this attempt fails as well

  const url = `/${page}/${id}/file`;

  return this.post(
    url,
    null,
    {
      body: form
    }
  );
}

我的架构如下所示:

  type File {
    id: ID!
    page: String!
    name: String
    url: String!
  }

  input FileUploadInput {
    id: ID!
    page: String!
    files: [Upload!]!
  }

  extend type Mutation {
    fileUpload(data: FileUploadInput!): File
  }

解析器

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

const singleFileUpload  (
  root,
  { data: { id, page, files } },
  { dataSources }
) => dataSources.files.fileUpload(id, page, files[0]);

module.exports = {
  Upload: GraphQLUpload,
  Mutation: {
    singleFileUpload
  }
};

标签: javascriptfile-uploadgraphqlmultipartform-dataform-data

解决方案


无论出于何种原因,graphql 提供的读取流不起作用,但将文件保存在本地,然后为该文件创建 readStream 成功。

    const { filename, createReadStream } = await file;
    const stream = await createReadStream();

    const { path } = await saveLocally(stream, filename); // this function pipes the stream to save it locally

    const newFile = await fs.createReadStream(path);

    const form = new FormData();
    form.append(
      'file',
      newFile
    );

    // I delete the file after I received a succesful response.
    await fs.unlink(path, (err, res) => {
      if (err) return err;
      return res;
    });


推荐阅读