【发布时间】:2018-07-08 06:47:01
【问题描述】:
我正在尝试将图像从 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太长错误。
我该如何解决? 将图像转换为 base64String 是发送它的最佳方式吗?
非常感谢。
【问题讨论】:
-
在查询字符串中发送图像是一个非常糟糕的主意。
-
这是我第一次,我想有很多更好的方法可以做到这一点,我只是问他们。
标签: c# image rest web-services xamarin.forms