我有一个用 C# 编写的 webform 应用程序,我想做的是在用户提交带有图像的 HTML 表单后,我将该图像发送到也用 C# 编写的 WCF Rest 服务。问题是当我在 Web 服务中获取图像时,它已损坏。
我想问题是我没有正确编码文件,但是在互联网上阅读了几天后,我还没有找到线索。
网络表单代码:
protected void Page_Load(object sender, EventArgs e)
{
HttpPostedFile image = Request.Files["imagen"];
string serverResponse = Send("mywebservice/postimage", "POST", Encoding.UTF8.GetBytes(StreamToString(image.InputStream)));
}
编辑(这种方式有效)
protected void Page_Load(object sender, EventArgs e)
{
HttpPostedFile image = Request.Files["imagen"];
MemoryStream ms = new MemoryStream();
image.InputStream.CopyTo(ms);
byte[] bytes = ms.ToArray();
string serverResponse = Send("mywebservice/postimage", "POST", bytes);
}
public int Send(string url, string method, byte[] data)
{
string serverResponse = "";
HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create(url);
newRequest.ContentType = "image/jpeg";
newRequest.Method = method;
newRequest.Timeout = 10000;
if (newRequest.Method == "POST" || newRequest.Method == "PUT")
{
Stream reqStream = newRequest.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
WSMessageEnt wsMessageEnt = new WSMessageEnt();
try
{
HttpWebResponse webResponse;
webResponse = (HttpWebResponse)newRequest.GetResponse();
Stream dataStream = webResponse.GetResponseStream();
serverResponse = new StreamReader(dataStream).ReadToEnd();
}
catch (WebException we)
{
}
return serverResponse;
}
public static string StreamToString(Stream data)
{
StreamReader reader = new StreamReader(data);
string body = reader.ReadToEnd();
reader.Close();
reader.Dispose();
return body;
}
网络服务代码:
[WebInvoke(UriTemplate = "upload-user-image", Method = "POST")]
public Stream UploadUserImage(Stream streamdata)
{
System.Drawing.Image img = System.Drawing.Image.FromStream(streamImagen, true);
// here I get a format error
}