【发布时间】:2020-10-09 18:05:44
【问题描述】:
我有这个 API,我在其中接收图像以将其保存在存储服务器中。我一直在测试邮递员的功能并且工作得很好。但是当涉及到移动应用时,它不会发送图像。
here you can see the Postman POST request
xamarin 应用的代码是下一个
var content = new MultipartFormDataContent();
var stream = File.OpenRead(_mediaFile.Path);
var streamcontent = new StreamContent(stream);
content.Add(streamcontent, "picture");
var client = new HttpClient();
HttpResponseMessage response = await cliente.PostAsync($"http://localhost:200/api/.../picture", content);
string result = response.Content.ReadAsStringAsync().Result;
Response responseData = JsonConvert.DeserializeObject<Response>(result);
if (response.IsSuccessStatusCode)
{
await Application.Current.MainPage.DisplayAlert("Correcto", "Imagen subida Correctamentel!", "OK");
_mediaFile = null;
terminado.IsEnabled = true;
}
else
{
terminado.IsEnabled = true;
await Application.Current.MainPage.DisplayAlert("Error", "Opps algo ocuirrio mal!", "OK"); }
正如您在邮递员中看到的那样,键 picture 接收图像名称。我也用 curl 试过了,效果很好:
curl -X POST "http://localhost:200/api/.../picture" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "picture=@version1.jpeg;type=image/jpeg"
【问题讨论】:
-
您的请求是否到达了服务器?您是否收到 HTTP 响应代码或超时?在移动客户端中使用“localhost”通常不是一个好主意。尝试使用服务器的 IP 或 FQDN
-
是的,它给了我这个错误:StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
-
另外,我注意到 Postman 为大多数语言创建了示例代码。它在控制台中运行良好,但使用 RestSharp 而不是 HttpClient。反正我要试试
-
您是否尝试添加文件名?
content.Add(streamcontent, "picture", "picture.jpg"); -
你解决了吗?
标签: c# api web-services xamarin dotnet-httpclient