【问题标题】:Unable to Pass Image in HTTP POST in a HTTP Web Request in ASP.NET无法在 ASP.NET 中的 HTTP Web 请求中的 HTTP POST 中传递图像
【发布时间】:2011-07-02 07:09:49
【问题描述】:

我无法将图像转换为字节并将其保存在数据库中。

这里是描述,

我有一张图片将使用 HTTP POST 从远程设备发送到 Web 服务器。

所以我正在做的是让他们将图像发送给我。

由于数据是在 POST 中发送的,我假设他们会通过使用将字节转换为字符串来向我发送字节

字节[] img = FileUpload1.FileBytes; 编码 enc = Encoding.ASCII; 字符串 img = enc.GetString(img);

然后他们使用 HTTPWebRequest 发出 WebRequest 并将此图像附加到 HTTP POST 中。

发出请求的完整代码---

    WebRequest request = WebRequest.Create(url);
    request.Method = "POST";


    //Create the POST Data

    FileUpload img = (FileUpload)imgUpload;
    Byte[] imgByte = null;
    if (img.HasFile && img.PostedFile != null)
    {
        imgByte = imgUpload.FileBytes;
    }
    string imgPh = null;
    Encoding enc = Encoding.ASCII;
    if (imgByte != null)
    {
        imgPh = enc.GetString(imgByte);
    }
    string postData = "sid=8062BD53EB4552AD6D0FBB7E5DC5B7AF&status=Y&uid=123456789012&fname=Dinesh Singh&lname=Malik&ftname=Balwan&yrbirth=1988&gender=Male&address1=Address1&address2=Address2&address3=Address3&address4=Address4&imagePh=" + imgPh;


    byte[] post = Encoding.UTF8.GetBytes(postData);


    //Set the Content Type
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = post.Length;

    Stream reqdataStream = request.GetRequestStream();
    // Write the data to the request stream.
    reqdataStream.Write(post, 0, post.Length);

    reqdataStream.Close();

    // If required by the server, set the credentials.
    request.Credentials = CredentialCache.DefaultCredentials;
    WebResponse response = null;
    try
    {
        // Get the response.
        response = request.GetResponse();

    }
    catch (Exception ex)
    {
        Response.Write("Error Occured.");
    }

在发出请求的页面上,我再次将此图像转换为字节使用

    Encoding enc = Encoding.ASCII;

    byte[] imagePhoto = enc.GetBytes(postData["imageph"]);

从这里我将它保存到我的数据库中

但是当我使用处理程序检索图像时,它不显示图像。


问题是图像从 byte[] 转换为 string,然后在 Web 服务器上将 string 转换为 byte[]。 (因为当我在服务器上使用 TestPage 直接保存图像而不进行此转换时,它会显示图像。)

那么我在这方面做错了什么。

上述代码中还有什么方法可以获取 Web 服务器接收到的 HTTP Post 数据(检索 HTTP 标头)。 我想检索收到的这些数据以将其发送回其他开发,以便在设备上以与我在 HTTP Web 请求 URL 中收到的格式相同的格式开发请求

任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net httpwebrequest http-headers


    【解决方案1】:

    好吧,我想我终于想通了。

    我所做的是-

    Image -> byte[] -> Convert.ToBase64String -> 将字符串数据附加到 Post 请求

    在服务器上-

    获取 Post 数据 -> Convert.FromBase64String -> byte[] -> 插入数据库

    效果很好...:)

    谢谢

    【讨论】:

      猜你喜欢
      • 2013-08-09
      • 2019-09-04
      • 2021-03-31
      • 2016-12-31
      • 2018-08-02
      • 2016-01-25
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      相关资源
      最近更新 更多