【问题标题】:Uploading an image using C# and WebRequest?使用 C# 和 WebRequest 上传图像?
【发布时间】:2010-01-11 18:37:11
【问题描述】:

这是 Python 中的工作代码(使用 cURL):

#!/usr/bin/python

import pycurl

c = pycurl.Curl()
values = [
          ("key", "YOUR_API_KEY"),
          ("image", (c.FORM_FILE, "file.png"))]
# OR:     ("image", "http://example.com/example.jpg"))]
# OR:     ("image", "BASE64_ENCODED_STRING"))]

c.setopt(c.URL, "http://imgur.com/api/upload.xml")
c.setopt(c.HTTPPOST, values)

c.perform()
c.close()

这是我在 C# 中所拥有的:

public void UploadImage()
    {
        //I think this line is doing something wrong.
        //byte[] x = File.ReadAllBytes(@"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\hotness2.jpg");

        //If I do it like this, using a direct URL everything works fine.
        string parameters = @"key=1b9189df79bf3f8dff2125c22834210903&image=http://static.reddit.com/reddit.com.header.png"; //Convert.ToBase64String(x);
        WebRequest webRequest = WebRequest.Create(new Uri("http://imgur.com/api/upload"));

        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(parameters);

        Stream os = null;
        try
        { // send the Post
            webRequest.ContentLength = bytes.Length;   //Count bytes to send
            os = webRequest.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);         //Send it
        }
        catch (WebException ex)
        {
            MessageBox.Show(ex.Message, "HttpPost: Request error");

        }
        finally
        {
            if (os != null)
            {
                os.Close();
            }
        }

        try
        { // get the response
            WebResponse webResponse = webRequest.GetResponse();

            StreamReader sr = new StreamReader(webResponse.GetResponseStream());
            MessageBox.Show(sr.ReadToEnd().Trim());
        }
        catch (WebException ex)
        {
            MessageBox.Show(ex.Message, "HttpPost: Response error");                  
        }            

    }

现在,我注意到当我将参数字符串中的 API 密钥更改为“239231”或任何数字时,我得到的响应是:“无效的 API 密钥”。所以我认为某些事情一定是正常的。

我放置了我的正确 API 密钥,现在我得到了不同的响应:“无效的图像格式。请尝试上传 JPEG 图像。”

我使用的服务几乎接受所有图像格式,因此我 100% 确定错误出在我发送文件的方式上。有人能解释一下吗?

编辑!!!

事实证明,当我上传 JPG 图像时,我得到了那个灰色框的东西。如果我上传一个大的 jpg 图像,我什么也得不到。例如:http://i.imgur.com/gFsUY.jpg

当我上传 PNG 时,上传的图片甚至不显示。

我确定问题出在编码上。我能做什么?

编辑 2!!!

现在我 100% 确定问题出在方法的第一行。 File.ReadAllBytes() 一定是做错了什么。如果我上传一个 URL 文件,一切都很好:http://imgur.com/sVH61.png

我想知道我应该使用什么编码。 :S

【问题讨论】:

  • 尝试使用 Fiddler 等工具查看从 Python 执行代码时如何发布数据。并且,查看从 .net 完成时请求是如何与数据一起发送的。这应该可以帮助您找到差异并在以后解决问题。

标签: c# post httpwebrequest webrequest


【解决方案1】:

试试这个:

string file = @"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\Avatar.png";
string parameters = @"key=1df918979bf3f8dff2125c22834210903&image=" +
    Convert.ToBase64String(File.ReadAllBytes(file));

【讨论】:

  • 这有点奏效。我想我在完成读取所有字节之前发送了文件,因为我收到了这张图片:i.imgur.com/hXIfq.jpg
  • 也许您应该向您的 API 提供商询问,或者您当前的图像已损坏,或者尝试上传 JPEG 图像
  • 我不知道上传出了什么问题。看看这张图片:i.imgur.com/y0WVP.jpg 如果你注意到,顶部有一些图片,也许我关闭连接太快了?我该如何检查?
  • 我得到一个响应 OK,这是预期的响应,它甚至给了我上传图像的链接。我认为问题在于图像的编码。 :S
  • FileInfo fi = new FileInfo(path);字节[] 内容 = 新字节[(int)fi.Length]; new FileStream(path, FileMode.Open).Read(content, 0, content.Length);
【解决方案2】:

您应该正确地形成一个多部分的 POST 请求。在此处查看示例:Upload files with HTTPWebrequest (multipart/form-data)

【讨论】:

  • 聪明的-1ers可以给个理由吗? +1 平衡。
  • 是的,对于像文件这样的大文件,绝对要使用 multipart。
【解决方案3】:

读取 API 中发布的图片

public IHttpActionResult UpdatePhysicianImage(HttpRequestMessage request)
    {
        try
        {
            var form = HttpContext.Current.Request.Form;
            var model = JsonConvert.DeserializeObject<UserPic>(form["json"].ToString());
            bool istoken = _appdevice.GettokenID(model.DeviceId);
            if (!istoken)
            {
                statuscode = 0;
                message = ErrorMessage.TockenNotvalid;
                goto invalidtoken;
            }
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    // var filePath = uploadPath + postedFile.FileName;
                    //  string fileUrl = Utility.AbsolutePath("~/Data/User/" + model.UserId.ToString());
                    string fileUrl = Utility.AbsolutePath("~/" + Utility.UserDataFolder(model.UserId, "Document"));
                    if (!Directory.Exists(fileUrl))
                    {
                        Directory.CreateDirectory(fileUrl);
                        Directory.CreateDirectory(fileUrl + "\\" + "Document");
                        Directory.CreateDirectory(fileUrl + "\\" + "License");
                        Directory.CreateDirectory(fileUrl + "\\" + "Profile");
                    }
                    string imageUrl = postedFile.FileName;
                    string naviPath = Utility.ProfileImagePath(model.UserId, imageUrl);
                    var path = Utility.AbsolutePath("~/" + naviPath);
                    postedFile.SaveAs(path);
                    docfiles.Add(path);
                    if (model.RoleId == 2)
                    {
                        var doctorEntity = _doctorProfile.GetNameVideoChat(model.UserId);
                        doctorEntity.ProfileImagePath = naviPath;
                        _doctorProfile.UpdateDoctorUpdProfile(doctorEntity);
                    }
                    else
                    {
                        var patientEntity = _PatientProfile.GetPatientByUserProfileId(model.UserId);
                        patientEntity.TumbImagePath = naviPath;
                        _PatientProfile.UpdatePatient(patientEntity);
                    }
                }
                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
        catch (Exception e)
        {
            statuscode = 0;
            message = "Error" + e.Message;
        }
    invalidtoken:
        return Json(modeldata.GetData(statuscode, message));
    }

【讨论】:

    【解决方案4】:

    尝试改变:-

    "application/x-www-form-urlencoded"
    

    "multipart/form-data"
    

    【讨论】:

    • @SergioTapia 那么您实际上必须将信息作为多部分发送。
    【解决方案5】:

    尝试将 jpg 的内容类型添加到您的多部分边界中。

    见这个网址的例子(在最后)

    http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

    【讨论】:

      【解决方案6】:

      在黑暗中拍摄,但可能会创建一个 Image 实例,将文件保存到 Stream 并使用它将字节读入数组然后上传。

      如:

      Image i = System.Drawing.Image.FromFile("wut.jpg");
      Stream stm = new Stream();
      System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
      System.Drawing.Imaging.EncoderParameters paramz = new System.Drawing.Imaging.EncoderParameters(1);
      myEncoderParameter = new EncoderParameter(myEncoder, 100L);
      paramz.Param[0] = myEncoderParameter;
      i.Save(stm, System.Drawing.Imaging.ImageFormat.Jpeg, paramz);
      /* I'm lazy: code for reading Stream into byte[] here */
      

      【讨论】:

        猜你喜欢
        • 2016-04-20
        • 1970-01-01
        • 2013-01-08
        • 2020-07-02
        • 1970-01-01
        • 2014-02-25
        • 2011-01-03
        • 2011-05-20
        • 1970-01-01
        相关资源
        最近更新 更多