[英]c# Send image from WPF to WebAPI
I have a WebAPI 2.1 service (ASP.Net MVC 4) that receive and image and related data. 我有一个WebAPI 2.1服务(ASP.Net MVC 4),用于接收图像和相关数据。 I need to send this image from WPF application, but I get 404 not found error.
我需要从WPF应用程序发送此图像,但出现404 not found错误。
Server side 服务器端
[HttpPost]
[Route("api/StoreImage")]
public string StoreImage(string id, string tr, string image)
{
// Store image on server...
return "OK";
}
Client side 客户端
public bool SendData(decimal id, int time, byte[] image)
{
string url = "http://localhost:12345/api/StoreImage";
var wc = new WebClient();
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var parameters = new NameValueCollection()
{
{ "id", id.ToString() },
{ "tr", time.ToString() },
{ "image", Convert.ToBase64String(image) }
};
var res=wc.UploadValues(url, "POST", parameters);
return true;
}
The url exists, I thing I need to encode to json format, but I don't know how. 网址存在,我需要将其编码为json格式,但我不知道如何。
Thanks for your time! 谢谢你的时间!
The method parameters in your case are received in QueryString
form. 您所用的方法参数以
QueryString
形式接收。
I would suggest you turn the parameters list into one single object like this: 我建议您将参数列表变成单个对象,如下所示:
public class PhotoUploadRequest
{
public string id;
public string tr;
public string image;
}
Then in you API convert the string to buffer from Base64String
like this: 然后在您的API中将字符串从
Base64String
转换为缓冲区,如下所示:
var buffer = Convert.FromBase64String(request.image);
Then cast it to HttpPostedFileBase
然后将其转换为
HttpPostedFileBase
HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(buffer);
Now you have the image file. 现在您有了图像文件。 Do whatever you want.
做你想做的。
Full Code here: 完整代码在这里:
[HttpPost]
[Route("api/StoreImage")]
public string StoreImage(PhotoUploadRequest request)
{
var buffer = Convert.FromBase64String(request.image);
HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(buffer);
//Do whatever you want with filename and its binaray data.
try
{
if (objFile != null && objFile.ContentLength > 0)
{
string path = "Set your desired path and file name";
objFile.SaveAs(path);
//Don't Forget to save path to DB
}
}
catch (Exception ex)
{
//HANDLE EXCEPTION
}
return "OK";
}
Edit: I forgot to add the Code for MemoryPostedFile
class 编辑:我忘记为
MemoryPostedFile
类添加代码
public class MemoryPostedFile : HttpPostedFileBase
{
private readonly byte[] fileBytes;
public MemoryPostedFile(byte[] fileBytes, string fileName = null)
{
this.fileBytes = fileBytes;
this.FileName = fileName;
this.InputStream = new MemoryStream(fileBytes);
}
public override void SaveAs(string filename)
{
File.WriteAllBytes(filename, fileBytes);
}
public override string ContentType => base.ContentType;
public override int ContentLength => fileBytes.Length;
public override string FileName { get; }
public override Stream InputStream { get; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.