向前发布的图像到WCF REST服务



我有一个用C#写的WebForm应用程序,我想做的是用户提交带有图像的HTML表单后,我将该图像发送到WCF REST服务也在C#中编写的WCF REST服务。。问题是当我在Web服务中获取图像时,这将被损坏。

我想问题是我无法正确编码文件,但是在互联网上阅读几天后,我没有找到线索。

WebForm代码:

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;
}

WebService代码:

[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
}

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

而不是这样做:

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

尝试做

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

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

相关内容

  • 没有找到相关文章

最新更新