javascript - 当我尝试将其发送到服务器时,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
}
};
解决方案
无论出于何种原因,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;
});
推荐阅读
- python - Numpy 连接中的内存错误 (np.concatenate)
- google-cloud-platform - 如何在谷歌云 sql 上下载 postgres 数据库的架构?
- python - 如何将熊猫数据框中的字符串转换为浮点数或整数
- java - SpringBoot中多个UnicastProcessor之间的消息传递
- database - MongoDB 从每个组中采样特定时间
- angular - 在 inetllij idea 中使用 Karma 运行 Angular 测试
- java - com.fasterxml.jackson.databind.exc.MismatchedInputException:无法构造 java 类的实例
- arrays - 将数组作为参数传递给方法
- ios - 位码未包含在我的框架中
- javascript - 带有承诺的条件可观察调用