使用POST发送图像

我有一个WPF应用程序和一个ASP.NET MVC站点。 WPF应用程序使用Kinect捕获图像,这些图像保存为文件。 我想要做的是将文件从WPF应用程序发送到ASP.NET MVC站点。

我尝试了以下从图像文件中获取字节并使用Base64将其转换为字符串,然后在另一侧尝试将字符串转换回字节然后再返回到文件。 除了最后的文件已损坏且无法加载外,整个过程仍然有效。

也是发送文件的正确方法,或者我最好尝试使用套接字?

WPF应用程序

var imageUrl = "http://127.0.0.1:18710/Home/Index"; //byte[] imageBytes = set.getImageBytes(); byte[] imb = System.Text.Encoding.UTF8.GetBytes("imagename=" + ImageName + ".png&image=" + Convert.ToBase64String(File.ReadAllBytes(ImageName + ".png"))); var imageReq = (HttpWebRequest)WebRequest.Create(imageUrl); imageReq.Method = "POST"; imageReq.ContentType = "application/x-www-form-urlencoded"; imageReq.ContentLength = imb.Length; using (Stream os = imageReq.GetRequestStream()) { os.Write(imb, 0, imb.Length); } 

ASP.NET MVC站点

 if (image != null && imagename != null) { System.IO.File.WriteAllBytes(@"c:\" + imagename, Convert.FromBase64String(image)); } 

你正在用编码做一些奇怪的事情。 如果您将文件名作为标题传递,可能会更好。您可以通过使用HttpContext.Current.Request在MVC端获取文件名。 然后,只需更改您在wpf应用程序中编写的RequestStream,即可:

byte[] imb = File.ReadAllBytes(ImageName + ".png")));