我想上传图片到 apollo-server
服务器突变模式,“创建帖子”获取文本和文件,并应存储文件并创建帖子
const mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
createPost: {
description: 'Create a new Post',
type: GraphQLID,
args: {
text:{
description:"description",
type:GraphQLString
},
files: {
description: 'images and videos',
type: GraphQLList(GraphQLUpload!)
},
},
async resolve(parent, { files }) {
console.log(files)
return true;
},
},
},
})
ViewModel 有名为“submit”的方法应该调用mutation 文本是字符串,它是变异的文本 URIs 是图像 uri
fun submit(){
viewModelScope.launch {
try {
apolloClient.mutate(CreatePostMutation(text.toInput(),files = URIs.mapIndexed() {index,uri -> uri.toFileUpload(context,"$index.png","image/png") })).await()
}catch (error:ApolloException){
Log.i("lol",error.message!!)
}
}
}
uri.toFileUpload 将内容 uri 转换为 inputStream 然后调用 inputStream.toFileUpload
fun Uri.toFileUpload(context:Context,name:String,mimeType: String): FileUpload {
return context.contentResolver.openInputStream(this)!!.toFileUpload(mimeType,name)
}
inputStream.toFileUpload 将 inputStream 转换为 FileUpload
fun InputStream.toFileUpload(mimetype:String,name:String):FileUpload{
val inputStream = this
return object : FileUpload(mimetype) {
override fun contentLength() = inputStream.available().toLong()
override fun fileName() = name
override fun writeTo(sink: BufferedSink) {
sink.writeAll(inputStream.source().buffer())
}
}
}
我在提交时遇到此错误
BadRequestError: Missing multipart field ‘operations’ (https://github.com/jaydenseric/graphql-multipart-request-spec)