首页 > 解决方案 > 通过 graphql 上传文件,设置服务器端和客户端,并通过 curl、postman 和客户端 react 应用程序进行查询

问题描述

如何通过graphql和curl上传文件?出现 F: command not found 之类的错误

 curl http://localhost:8888/graphql \  
-F operations='{ "query": "mutation($files: [Upload!]!) { multipleUpload(files: $files) { id, name, content } }", "variables": { "files": [null, null] } }' \
-F map='{ "0": ["variables.files.0"], "1": ["variables.files.1"] }' \
-F 0=@./example/fileupload/testfiles/a.txt \
-F 1=@./example/fileupload/testfiles/c.txt 

标签: curlfile-uploadgraphql

解决方案


使用 gqlgen 获得了一个工作版本,其中有一个文件上传示例 https://github.com/99designs/gqlgen/tree/master/example/fileupload

并希望通过 https://github.com/jaydenseric/graphql-multipart-request-spec上的规范来实现它 注意这个规范为您提供了一个潜在项目列表,您可以在每个处理文件上传时为服务器和客户端关注.

示例 curl 请求,尽管根据您实现它的方式,您可能还需要通过 -H 包含标头。当您继续另一行时,请注意在 \ 之后不要有任何空格,否则您将收到 F: command not found 之类的错误)。我包括 -v 以获取更多详细信息,还包括 -L 以便如果有任何重定向,您仍然可以正确地在控制台中获得输出。

curl -v -L http://localhost:8087/graphql \
-F operations='{ "query": "mutation($files: [Upload!]!) { multipleUpload(files: $files) { id, name, content } }", "variables": { "files": [null, null] } }' \
-F map='{ "0": ["variables.files.0"], "1": ["variables.files.1"] }' \
-F 0=@./example/fileupload/testfiles/a.txt \
-F 1=@./example/fileupload/testfiles/c.txt 

这负责查询服务器,我也可以使用如下设置通过 Postman 访问它 postman 配置,文件上传 graphql 查询

从客户端来看,如果使用 apollo,一个关键点似乎是从https://github.com/jaydenseric/apollo-upload-client添加项目 apollo-upload-client ,用 createUploadLink({ uri: .. .}) 在 App.js 中,然后重新启动客户端。在我这样做之后,示例组件https://github.com/jaydenseric/apollo-upload-examples/blob/master/app/components/UploadFileList.js终于为我工作了。

即使突变查询说它使用 Upload 类型,您也不需要为它创建接口,它应该从服务器处理(因此,如果您收到类似于 can't convert map [string] interface 的错误消息,似乎{} 上传与发生的实际错误无关)

帮助您入门的其他提示:当在 graphql 查询中加载数据时,在 golang 中,您可以通过提取内容 ([]byte) 来编写文件,或者可以将其作为 Blob 保存到 sql server。

    content, err := ioutil.ReadAll(file.File)
    ...
    err := ioutil.WriteFile("/tmp/outputFile", content, 0644)

并且在加载文件时,您可以将数据作为字符串加载回来,然后在 writeFile func 中输入 []byte(file.Content)


推荐阅读