【问题标题】:Upload image from mobile app to API with multipart/form-data使用 multipart/form-data 将图像从移动应用程序上传到 API
【发布时间】: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


【解决方案1】:

我已经设法让它工作了,但使用的是 RestSharp 库而不是 HttpClient:

var client = new RestClient("192.168.0.2"); //the ip of your REST API
var request = new RestRequest(Method.POST); 
request.AddHeader("Content-Type", "multipart/form-data"); // I'm using multipart form data
request.AddHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLC"); // using JWT for auth
request.AddFile("pictureField", "/path/to/file"); //the path depends on which device you're using
IRestResponse response = client.Execute(request); 

非常直截了当,工作得很好。此外,“pictureField”取决于 API 所需的字段名称,文件路径不应硬编码。应根据所选图像在设备中的位置给出。

【讨论】:

  • 您好,您可以在有时间的时候标记答案,这将有助于其他有类似问题的人知道解决方案。 :-)
  • 抱歉,忘记了。完成:)
猜你喜欢
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 2011-03-22
  • 2019-01-06
  • 2011-04-22
  • 1970-01-01
相关资源
最近更新 更多