将图片发送到Rest服务Xamarin Forms

3

我尝试将Xamarin Forms中的图像发送到Rest WebApi,但没有成功。我正在使用Montemagno的CrossMedia插件。我通过以下方式将MediaFile转换为base64String:

if (photo != null)
{
    var stream = photo.GetStream();
    var bytes = new byte[stream.Length];
    await stream.ReadAsync(bytes, 0, (int)stream.Length);
    string imageBase64 = Convert.ToBase64String(bytes);
    Task<string> sendFotoResult = restClient.SendImage(imageBase64);
    string result = await sendFotoResult;
    if( ... )
}

这是我的SendImage函数:
public async Task<string> SendImage(string foto)
{
  try
  {
     // METHOD 1 
     var content = JsonConvert.SerializeObject(foto);
     string url = "http://myaddress/myWS/api/Home/SendImage?foto="+ content;
     var response = await _client.PostAsync(url, new StringContent(content, Encoding.UTF8, "application/json"));
     return response.ReasonPhrase.ToString();

     //METHOD 2
     var content = JsonConvert.SerializeObject(foto);
     string url = "http://myaddress/myWS/api/Home/SendImage?foto="+ content;
     var result = await _client.PostAsync(url, new StringContent(content, Encoding.UTF8, "application/json"));
     return result.ToString(); 
  }catch (Exception ex)
  {
    return ex.Message;
  }
}

方法1显示空参数错误,方法2获取URL过长错误。

我该如何解决这个问题?将图像转换为base64字符串是发送它的最佳方式吗?

非常感谢。


4
在查询字符串中发送图像是一个非常糟糕的想法。 - EvZ
这是我第一次,我猜可能有很多更好的方法来做这件事,我只是问了他们。 - Dracarys
2个回答

3

您不应该将图像发送到URI中。您需要做的是将图像发送到请求主体中。类似以下内容可以帮助您:

var client = new HttpClient();
var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(new MemoryStream(foto).ToArray()), "foto", "foto.jpg");

那么您需要在服务器端API上管理图像并将其转换回来。
编辑:我假设如果您还控制您的REST API,那么您必须试图从URI获取图像。 您不应该这样做,而是必须从内容中获取它。 这里有一个教程,会带您完成整个过程:https://jamessdixon.wordpress.com/2013/10/01/handling-images-in-webapi/ 此外,您应该像这样调用没有参数的POST方法:
string url = "http://myaddress/myWS/api/Home/"

如果您已经在Home控制器上管理POST请求以执行其他工作,那么您可以始终利用路由并调用类似以下的语句:
string url = "http://myaddress/myWS/api/Home/Images/"

ASP.NET中的路由管理非常简单,可以参考以下链接进行详细了解:https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
另外,如果您需要加强对REST标准的了解,我建议您查看以下页面,了解在设计RESTful API时应该做什么和不应该做什么:http://blog.octo.com/en/design-a-rest-api/。请注意保留原有的HTML标签。

也许使用MultipartFormDataContent()是正确的方式。如何以正确的方式编写URL? - Dracarys
当然,我已经加强了我的 REST 知识,你是对的。这是我第一次接触它,道路仍然很漫长。在此之前,您建议我如何修复它? - Dracarys
虽然你消失了,但是你的链接非常有用。我已经解决了,谢谢。 - Dracarys

0
您可以使用MultipartFormDataContent将图像部分添加到POST请求中,请尝试以下示例。
            var upfilebytes = DependencyService.Get<ILocalFileProvider>().GetFileBytes(FileUrl);
            MultipartFormDataContent content = new MultipartFormDataContent();
            ByteArrayContent baContent = new ByteArrayContent(upfilebytes);
            content.Add(baContent, "File", "attachment.png");
            var response = await client.PostAsync(url, content);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接