uploading image to imgur using c#
Uploading image to imgur.com using code below returns http 400 error code. My developer key is correct and I tried different image formats with sizes upto 70 kb. I also tried code example for c# given at http://api.imgur.com/examples but it also gives http 400. What might be the problem?
public XDocument Upload(string imageAsBase64String)
{
XDocument result = null;
using (var webClient = new WebClient())
{
var values = new NameValueCollection
{
{ "key", key },
{ "image", imageAsBase64String },
{ "type", "base64" },
};
byte[] response = webClient.UploadValues("http://api.imgur.com/2/upload.xml", "POST", values);
result = XDocument.Load(new MemoryStream(response));
}
return result;
}
EDIT: This is an ASP.NET MVC application and caller controller action is:
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
var imgService = new ImgUrImageService();
byte[] fileBytes = new byte[uploadFile.InputStream.Length];
Int64 byteCount = uploadFile.InputStream.Read(fileBytes, 0, (int)uploadFile.InputStream.Length);
uploadFile.InputStream.Close();
string开发者_如何转开发 fileContent = Convert.ToBase64String(fileBytes, 0, fileBytes.Length);
var response = imgService.Upload(fileContent);
}
return View();
}
Ok I found the reason. A proxy setting (for Fiddler) in my web.config file was causing the issue. Removing it solved the problem and my another issue too (related to recaptcha). Code is working like a charm.
If you modify your code to this:
public XDocument Upload(string imageAsBase64String)
{
XDocument result = null;
using (var webClient = new WebClient())
{
var values = new NameValueCollection
{
{ "key", key },
{ "image", imageAsBase64String }
};
byte[] response = webClient.UploadValues("http://api.imgur.com/2/upload.xml", "POST", values);
result = XDocument.Load(System.Xml.XmlReader.Create(new MemoryStream(response)));
}
return result;
}
Everything will work fine with an ANONYMOUS API key. To use the authenticated API you will have to create an OAuth token using your Consumer Key and Consumer Secret.
Imgur has some more information about the specific endpoints needed and some links to additional help here: http://api.imgur.com/auth
Your conversion code looks mostly fine, I have changed it slightly:
[HttpPost]
public ActionResult UploadImage(HttpPostedFile uploadFile)
{
if (uploadFile.ContentLength > 0)
{
var imgService = new ImgUrImageService();
byte[] fileBytes = new byte[uploadFile.ContentLength];
uploadFile.InputStream.Read(fileBytes, 0, fileBytes.Length);
uploadFile.InputStream.Close();
string fileContent = Convert.ToBase64String(fileBytes);
var response = imgService.Upload(fileContent);
}
return View();
}
In your original upload code you add an extra value of type, are you still adding this or did you switch your code to match my changed code above? I see no reason to add this value and I don't see where it's supported with imgur.
精彩评论