我有个问题。我想将图像和变量上传到我的网页,因此创建了以下代码:
using (var formContent = new MultipartFormDataContent("NKdKd9Yk"))
{
formContent.Headers.ContentType.MediaType = "multipart/form-data";
StringContent UserIdContent = new StringContent(App.User.Id.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");
formContent.Add(UserIdContent, "id");
StringContent CreatedImageContent = new StringContent(CreatedImage, Encoding.UTF8, "binary/octet-streOpenWriteam");
formContent.Add(CreatedImageContent , "image");
using (var client = new HttpClient())
{
try
{
// 4.. Execute the MultipartPostMethod
var message = await client.PostAsync(url, formContent);
// 5.a Receive the response
var result = await message.Content.ReadAsStringAsync();
if (result == "Success")
{
App.Current.MainPage = new SideMenuItems();
}
}
catch (Exception ex)
{
// Do what you want if it fails.
throw ex;
}
}
}
现在,这两个变量都已由服务器接收,但是image变量是设备上图像的路径,而不是图像本身。
我究竟做错了什么?
使用该路径获取图像流并使用流内容。
using (var formContent = new MultipartFormDataContent("NKdKd9Yk")) {
formContent.Headers.ContentType.MediaType = "multipart/form-data";
var id = App.User.Id.ToString();
StringContent UserIdContent = new StringContent(id, Encoding.UTF8, "application/x-www-form-urlencoded");
formContent.Add(UserIdContent, "id");
FileStream fs = System.IO.File.OpenRead(CreatedImage);
formContent.Add(new StreamContent(fs), "image");
using (var client = new HttpClient()) {
try {
// 4.. Execute the MultipartPostMethod
var message = await client.PostAsync(url, formContent);
// 5.a Receive the response
var result = await message.Content.ReadAsStringAsync();
if (result == "Success") {
App.Current.MainPage = new SideMenuItems();
}
} catch (Exception ex) {
// Do what you want if it fails.
throw ex;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句