2

使用以下代码将图像上传到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();
}
4

2 回答 2

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

使用匿名API 密钥,一切都会正常工作。要使用经过身份验证的 API,您必须使用您的 Consumer Key 和 Consumer Secret 创建一个 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 支持的位置。

于 2010-12-05T03:27:05.350 回答
1

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

于 2010-12-15T20:10:06.003 回答