gpt4 book ai didi

c# - 上传到 imgur.com

转载 作者:可可西里 更新时间:2023-11-01 08:19:53 24 4
gpt4 key购买 nike

Imgur 是一个提供API to upload 的图片上传网站

我的代码看起来与他们作为示例提供的 PHP 代码完全一样。然而,在他们的 php 代码中,它们是 http_build_query($pvars);

他们似乎在发布查询之前对其进行了 URLEncoding。编辑:请注意,我已更改为完整的 .NET 3.5 而不是客户端配置文件。这让我可以访问 system.web,所以我使用了 httputliity.urlencode()。这使得 api 返回“未发送图像”的“失败”。如果我不进行编码,那么 API 会返回带有图片链接的“okay”,但不会上传任何图片(如空白文件)。

如何修复我的代码以针对他们的 API 正常工作?

 Image image = Image.FromFile("C:\\Users\\Affan\\Pictures\\1509310.jpg");
MemoryStream ms = new MemoryStream();
// Convert Image to byte[]
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();

WebRequest wb = WebRequest.Create(new Uri("http://imgur.com/api/upload.xml"));
wb.ContentType = "application/x-www-form-urlencoded";
wb.Method = "POST";
wb.Timeout = 10000;
Console.WriteLine(imageBytes.Length);
string parameters = "key=433a1bf4743dd8d7845629b95b5ca1b4&image=" + Convert.ToBase64String(imageBytes);


Console.WriteLine("parameters: " + parameters.Length);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(parameters);
// byte[] bytes = Convert.FromBase64String(parameters);

System.IO.Stream os = null;
try { // send the Post
wb.ContentLength = bytes.Length; //Count bytes to send
os = wb.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
} catch (WebException ex) {
MessageBox.Show(ex.Message, "HttpPost: Request error");
Console.WriteLine(ex.Message);
} finally {
if (os != null) {
// os.Close();
}
}

try { // get the response
WebResponse webResponse = wb.GetResponse();

StreamReader sr = new StreamReader(webResponse.GetResponseStream());
//MessageBox.Show(sr.ReadToEnd().Trim());
Console.WriteLine(sr.ReadToEnd().Trim());
} catch (WebException ex) {
MessageBox.Show(ex.Message, "HttpPost: Response error");
}

最佳答案

我刚刚上传了这张图片

Hello World

使用此代码:

using (var w = new WebClient())
{
var values = new NameValueCollection
{
{ "key", "433a1bf4743dd8d7845629b95b5ca1b4" },
{ "image", Convert.ToBase64String(File.ReadAllBytes(@"hello.png")) }
};

byte[] response = w.UploadValues("http://imgur.com/api/upload.xml", values);

Console.WriteLine(XDocument.Load(new MemoryStream(response)));
}

您可能想现在更改您的 API key :-)

输出是:

<rsp stat="ok">
<image_hash>IWg2O</image_hash>
<delete_hash>fQAXiR2Fdq</delete_hash>
<original_image>http://i.imgur.com/IWg2O.png</original_image>
<large_thumbnail>http://i.imgur.com/IWg2Ol.jpg</large_thumbnail>
<small_thumbnail>http://i.imgur.com/IWg2Os.jpg</small_thumbnail>
<imgur_page>http://imgur.com/IWg2O</imgur_page>
<delete_page>http://imgur.com/delete/fQAXiR2Fdq</delete_page>
</rsp>

关于c# - 上传到 imgur.com,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2073519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com