使用c#将图像上传到imgur

时间:2010-12-05 00:32:13

标签: c# uploading imgur

使用以下代码将图片上传到imgur.com会返回http 400错误代码。我的开发人员密钥是正确的,我尝试了不同的图像格式,大小高达70 kb。 我还尝试了在http://api.imgur.com/examples给出的c#的代码示例,但它也提供了http 400。 可能是什么问题?

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;
}

编辑:这是一个ASP.NET MVC应用程序,调用者控制器操作是:

[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();
}

2 个答案:

答案 0 :(得分:1)

如果您将代码修改为:

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;
}

使用 ANONYMOUS API密钥,一切都会正常运行。要使用经过身份验证的API,您必须使用消费者密钥和消费者密钥创建OAuth令牌。

Imgur在此处提供了有关所需特定终端的更多信息以及一些指向其他帮助的链接:http://api.imgur.com/auth

您的转换代码看起来很好,我稍微改了一下:

[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();
}

在您的原始上传代码中,您添加了额外的类型值,是否仍然添加此内容,或者您​​是否切换代码以匹配上面更改的代码?我认为没有理由添加这个值,我不知道imgur支持它的位置。

答案 1 :(得分:1)

好的我找到了原因。我的web.config文件中的代理设置(对于Fiddler)导致了该问题。删除它解决了问题和我的另一个问题(与recaptcha相关)。代码就像一个魅力。