1

我有一个用 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
}
4

1 回答 1

1

可能是一个问题:您正在将字节流转换为字符串,然后再转换回字节流。图像字节是任意字节,可能会或可能不会映射到字符串,并且您在一次转换中使用的编码 (Encoding.Default) 可能与在另一次转换中使用的编码不同 (Encoding.UTF8)。

而不是这样做:

Encoding.UTF8.GetBytes(StreamToString(image.InputStream))

尝试做类似的事情

MemoryStream ms = new MemoryStream();
image.InputStream.CopyTo(ms);
byte[] bytes = ms.ToArray();

或者只是将流传递给并将Send其复制到请求流。

于 2012-10-30T17:24:28.970 回答