使用 multipart/form-data 将图片从移动应用上传到 API

Upload image from mobile app to API with multipart/form-data

我有这个 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"

我已经让它工作了,但是使用的是 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 所需的字段名称,文件路径不应硬编码。应该根据所选图像在设备中的位置给出。