我正在尝试使用graphql-dotnet上传图片文件,但它永远不会成功。
我正在使用GraphQLController中的文件对象:
var files = this.Request.Form.Files;
var executionOptions = new ExecutionOptions
{
Schema = _schema,
Query = queryToExecute,
Inputs = inputs,
UserContext = files,
OperationName = query.OperationName
};
在这里我的突变:
Field<UserGraphType>(
"uploadUserAvatar",
Description="Kullanıcı resmi yükleme.",
arguments: new QueryArguments(
new QueryArgument<NonNullGraphType<IntGraphType>> { Name = "Id", Description = "Identity Alanı" }
),
resolve: context => {
var file = context.UserContext.As<IFormCollection>();
var model = userService.UploadAvatar(context.GetArgument<int>("Id"),file);
return true;
}
);
我认为它接受了唯一的JSON。它不接受请求作为文件类型。
我也在使用React&amp;客户端的apollo-client。它在控制台中出错:
无法加载http://localhost:5000/graphql:请求的资源上没有“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:8080”访问。响应具有HTTP状态代码500.如果不透明响应满足您的需要,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。
我正在尝试发送这样的查询:
const { selectedFile,id } = this.state
this.props.uploadAvatar({
variables: {id},
file:selectedFile
}).then(result => {
console.log(result);
});
我能做些什么来实现这个目标?
答案 0 :(得分:0)
无法加载http://localhost:5000/graphql:否 &#39;访问控制允许来源&#39;标题出现在请求的上 资源。起源&#39; http://localhost:8080&#39;因此是不允许的 访问。
此错误意味着您需要启用CORS。
请参阅以下文档:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1
基本上你需要这两件事:
services.AddCors();
app.UseCors(builder =>
builder.WithOrigins("http://example.com"));
我还建议在GraphQL.Relay项目中查看这个Deserializer
辅助函数。它可以帮助您的服务器处理multipart/form-data
请求。然后,您可以使用已解析的查询信息和文件,并将其传递给DocumentExecutor
。
https://github.com/graphql-dotnet/relay/blob/master/src/GraphQL.Relay/Http/Deserializer.cs
public static class Deserializer
{
public static async Task<RelayRequest> Deserialize(Stream body, string contentType)
{
RelayRequest queries;
switch (contentType)
{
case "multipart/form-data":
queries = DeserializeFormData(body);
break;
case "application/json":
var stream = new StreamReader(body);
queries = DeserializeJson(await stream.ReadToEndAsync());
break;
default:
throw new ArgumentOutOfRangeException($"Unknown media type: {contentType}. Cannot deserialize the Http request");
}
return queries;
}
private static RelayRequest DeserializeJson(string stringContent)
{
if (stringContent[0] == '[')
return new RelayRequest(
JsonConvert.DeserializeObject<RelayQuery[]>(stringContent),
isBatched: true
);
if (stringContent[0] == '{')
return new RelayRequest() {
JsonConvert.DeserializeObject<RelayQuery>(stringContent)
};
throw new Exception("Unrecognized request json. GraphQL queries requests should be a single object, or an array of objects");
}
private static RelayRequest DeserializeFormData(Stream body)
{
var form = new MultipartFormDataParser(body);
var req = new RelayRequest()
{
Files = form.Files.Select(f => new HttpFile {
ContentDisposition = f.ContentDisposition,
ContentType = f.ContentType,
Data = f.Data,
FileName = f.FileName,
Name = f.Name
})
};
req.Add(new RelayQuery {
Query = form.Parameters.Find(p => p.Name == "query").Data,
Variables = form.Parameters.Find(p => p.Name == "variables").Data.ToInputs(),
});
return req;
}
}