GraphQL 中的图像上传
Posted
技术标签:
【中文标题】GraphQL 中的图像上传【英文标题】:Image Upload in GraphQL 【发布时间】:2017-06-04 03:31:38 【问题描述】:如何在 graphql 中处理图片上传
通过multer使用express route处理从graphql上传和查询以查看图像和其他数据
app.use('/graphql', upload);
app.use('/graphql', getData, graphqlHTTP(tokenData => (
schema,
pretty: true,
tokenData,
graphiql: true,
)));
【问题讨论】:
How would you do file uploads in a React-Relay app?的可能重复 同意,可能是重复的。文件是文件、图像或其他。 【参考方案1】:这是How would you do file uploads in a React-Relay app?的副本
简而言之,是的,您可以使用 react + relay 在 graphql 中上传文件。 需要编写Relay更新存储动作,例如:
onDrop: function(files)
files.forEach((file)=>
Relay.Store.commitUpdate(
new AddImageMutation(
file,
images: this.props.User,
),
onSuccess, onFailure
);
);
,
然后为 Relay 存储实现一个突变
class AddImageMutation extends Relay.Mutation
static fragments =
images: () => Relay.QL`
fragment on User
id,
`,
;
getMutation()
return Relay.QL`mutation introduceImage `;
getFiles()
return
file: this.props.file,
;
getVariables()
return
imageName: this.props.file.name,
;
getFatQuery()
return Relay.QL`
fragment on IntroduceImagePayload
User
images(first: 30)
edges
node
id,
,
newImageEdge,
`;
getConfigs()
return [
type: 'RANGE_ADD',
parentName: 'User',
parentID: this.props.images.id,
connectionName: 'images',
edgeName: 'newImageEdge',
rangeBehaviors:
'': 'prepend',
,
];
在您的服务器端架构中,预制更新
const imageMutation = Relay.mutationWithClientMutationId(
name: 'IntroduceImage',
inputFields:
imageName:
type: new GraphQL.GraphQLNonNull(GraphQL.GraphQLString),
,
,
outputFields:
newImageEdge:
type: ImageEdge,
resolve: (payload, args, options) =>
const file = options.rootValue.request.file;
//write the image to you disk
return uploadFile(file.buffer, filePath, filename)
.then(() =>
/* Find the offset for new edge*/
return Promise.all(
[(new myImages()).getAll(),
(new myImages()).getById(payload.insertId)])
.spread((allImages, newImage) =>
const newImageStr = JSON.stringify(newImage);
/* If edge is in list return index */
const offset = allImages.reduce((pre, ele, idx) =>
if (JSON.stringify(ele) === newImageStr)
return idx;
return pre;
, -1);
return
cursor: offset !== -1 ? Relay.offsetToCursor(offset) : null,
node: newImage,
;
);
);
,
,
User:
type: UserType,
resolve: () => (new myImages()).getAll(),
,
,
mutateAndGetPayload: (input) =>
//break the names to array.
let imageName = input.imageName.substring(0, input.imageName.lastIndexOf('.'));
const mimeType = input.imageName.substring(input.imageName.lastIndexOf('.'));
//wirte the image to database
return (new myImages())
.add(imageName)
.then(id =>
//prepare to wirte disk
return
insertId: id,
imgNmae: imageName,
;
);
,
);
上面的所有代码你都可以在这个 repo https://github.com/bfwg/relay-gallery 中找到它们 还有现场演示http://fanjin.io
【讨论】:
如果这个答案是重复的,你应该投票标记它并指向现有的答案,因为它基本上是一样的。以上是关于GraphQL 中的图像上传的主要内容,如果未能解决你的问题,请参考以下文章
如何将图像上传到 KeystoneJS GraphQL 端点?