当使用graphql-upload,然后尝试将返回数据发送到flask python服务器时,数据始终以主体而不是文件结尾。当我使用下面的graphql连接器时,标头会自动成功设置为content-type: multipart/form-data boundary etc....
。
我基于此示例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
}
};
答案 0 :(得分:0)
无论出于何种原因,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
);
let url = parent
? `${this.baseURL}/${name}/${id}/files/${parent}`
: `${this.baseURL}/${name}/${id}/files`;
// I delete the file after I received a succesful response.
await fs.unlink(path, (err, res) => {
if (err) return err;
return res;
});