2010-01-11 58 views
2

这里是用Python运行的代码(使用卷曲):使用C#和WebRequest上传图像?

#!/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图片,我什么都没有收到。例如:​​

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

我确定问题是编码。我能做什么?

编辑2!

现在我100%确定问题在于方法的第一行。 File.ReadAllBytes()必须做错了什么。如果我上传的URL文件,每一个作品桃子:http://imgur.com/sVH61.png

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

+0

使用的工具,如提琴手看到的数据是如何贴出来,当代码从Python的执行尝试发布。并且,看看如何在.net中完成请求与数据一起发送。这应该有助于您找到差异并修复后面的内容。 – shahkalpesh 2010-01-12 05:42:34

回答

2

试试这个:

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)); 
+0

这工作,有点。我想在我完成读取所有字节之前发送文件,因为我收到了这个图像:http://i.imgur.com/hXIfq.jpg – 2010-01-11 18:51:10

+0

也许你应该问你的API提供商,或者你当前的图像被破坏,或尝试上载JPEG图像 – 2010-01-11 18:58:20

+0

我不知道上传出了什么问题。查看此图像:http://i.imgur.com/y0WVP.jpg如果您注意到,顶部有一点图像,也许我很快关闭连接?我怎样才能检查这个? – 2010-01-11 18:59:28

0

尝试改变: -

"application/x-www-form-urlencoded" 

"multipart/form-data" 
+0

现在,我收到一个错误:“错误,没有图像发送。” – 2010-01-11 18:45:42

+0

@SergioTapia然后,您确实必须将信息作为多部分发送。 – Nyerguds 2016-04-12 10:20:57

-1

在黑暗中拍摄,但也许创建一个图像的实例,将文件保存到一个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 */ 
1

读取图像通过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)); 
    }