Search code examples
c#apiimgur

Uploading images from Imgur API gives 400 bad request


I've looked up the API for Imgur and it said that it accepts a binary file when uploading images, and I have my code as such:

 private async Task Upload()
        {
            var openfiledialog = new OpenFileDialog();
            openfiledialog.Filter = "Image files (*.png) | *.png";
            if (openfiledialog.ShowDialog() == DialogResult.OK)
            {
                using (var stream = openfiledialog.OpenFile())
                {
                    byte[] imageBytes = new byte[stream.Length];
                    stream.Read(imageBytes, 0, imageBytes.Length);
                    var httpclient = new HttpClient();
                    httpclient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Client-ID", "MYCLIENTID");               
                    httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/octet-stream");
                    var status = await httpclient.PostAsync("https://api.imgur.com/3/upload", new ByteArrayContent(imageBytes));
                    
                }
            }
        }

But, it give me a 400 bad request, and I am not sure what I am doing wrong.

Response body


Solution

  • I managed to fix it by converting the image to base64 and using text/plain content type header.

     public async Task<string> UploadImage(string base64Image)
            {
                var httpclient = new HttpClient();
                httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Client-ID", "MYCLIENTID");
                httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "text/plain");
                var response = await httpclient.PostAsync("https://api.imgur.com/3/Image", new StringContent(base64Image));
                var stringcontent = await response.Content.ReadAsStringAsync();
                var ImgurResponseModel = JsonConvert.DeserializeObject<ImgurResponseModel>(stringcontent);
                return ImgurResponseModel.Data.Link;         
            }