Search code examples
asp.nethttpclientimgur

Can't upload an image to imgur with asp.net


I am working on project that I need to upload image to imgur.com, I wrote the code but it didn't work when came to posting part! any suggestions?

 private async Task<string> UploadImageAsync(string imageDataBase64String)
    {
        client = new HttpClient();
        client.BaseAddress = new Uri("https://api.imgur.com/3/");
        client.DefaultRequestHeaders.Add("Authorization", "Client-id " + ClientID);
        HttpContent contentPost = new StringContent(imageDataBase64String);
        var response = await client.PostAsync("image", contentPost);
        response.EnsureSuccessStatusCode();
        var responseContent = await response.Content.ReadAsStringAsync();
        var model = new JavaScriptSerializer().Deserialize<dynamic>(responseContent);
        var imageLink = model["data"]["link"];
        return imageLink;
    }

Solution

  • I'm working on similar project and here is how I did it.

    • Create a view models for imgur response:

      public class ImgurResponseViewModel
      {
          public ImgurImageDataViewModel Data { get; set; }
          public bool Success { get; set; }
          public int Status { get; set; }
      }
      
    • Create a view models for image data:

      public class ImgurImageDataViewModel
      {
          public string Id { get; set; }
          public string Title { get; set; }
          public string Description { get; set; }
          public string Datetime { get; set; }
          public string Type { get; set; }
          public bool Animated { get; set; }
          public int Width { get; set; }
          public int Height { get; set; }
          public int Size { get; set; }
          public int Views { get; set; }
          public int Bandwidth { get; set; }
          public string Ddeletehash { get; set; }
          public string Section { get; set; }
          public string Link { get; set; }
          public string Account_url { get; set; }
          public int Aaccount_id { get; set; }
      }
      
    • And this is the code for uploading:

      private async Task<string> UploadImageAsync(string imageDataBase64String)
      {
          byte[] response;
          using (var client = new WebClient())
          {
              string clientID = "YourClientID";
              client.Headers.Add("Authorization", "Client-ID " + clientID);
              var values = new NameValueCollection { { "image", imageDataBase64String } };
              response = await client.UploadValuesTaskAsync("https://api.imgur.com/3/upload", values);
          }
      
          var result = JsonConvert.DeserializeObject<ImgurResponseViewModel>(Encoding.ASCII.GetString(response));
      
          return result.Data.Link;
      }
      

    I hope this will help you.