将发布的图像转发给WCF Rest Service

时间:2012-10-30 17:06:49

标签: c# wcf httpwebrequest

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

1 个答案:

答案 0 :(得分:1)

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

而不是这样做:

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

尝试做类似

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

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