Python での作業コード (cURL を使用) は次のとおりです。
#!/usr/bin/python
import pycurl
c = pycurl.Curl()
values = [
("key", "YOUR_API_KEY"),
("image", (c.FORM_FILE, "file.png"))]
# OR: ("image", "http://example.com/example.jpg"))]
# OR: ("image", "BASE64_ENCODED_STRING"))]
c.setopt(c.URL, "http://imgur.com/api/upload.xml")
c.setopt(c.HTTPPOST, values)
c.perform()
c.close()
これが私がC#で持っているものです:
public void UploadImage()
{
//I think this line is doing something wrong.
//byte[] x = File.ReadAllBytes(@"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\hotness2.jpg");
//If I do it like this, using a direct URL everything works fine.
string parameters = @"key=1b9189df79bf3f8dff2125c22834210903&image=http://static.reddit.com/reddit.com.header.png"; //Convert.ToBase64String(x);
WebRequest webRequest = WebRequest.Create(new Uri("http://imgur.com/api/upload"));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error");
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
MessageBox.Show(sr.ReadToEnd().Trim());
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error");
}
}
ここで、パラメータ文字列の API キーを「239231」などの数値に変更すると、「無効な API キー」という応答が返されたことに気付きました。ですから、何かがうまくいっているに違いないと思います。
正しいAPI キーを配置したところ、 「無効な画像形式です。JPEG 画像をアップロードしてみてください。」という別の応答が返されました。
私が使用しているサービスはほぼすべての画像形式を受け入れるため、ファイルの送信方法にエラーがあることは 100% 確信しています。誰でも光を当てることができますか?
編集!!!
JPG画像をアップロードすると、灰色のボックスが表示されます。大きなjpg画像をアップロードしても、何も得られません。例: http://i.imgur.com/gFsUY.jpg
PNG をアップロードすると、アップロードされた画像が表示されません。
問題はエンコーディングだと確信しています。私に何ができる?
編集2!!!
これで、メソッドの最初の行に問題があることは 100% 確信できました。File.ReadAllBytes() は何か間違ったことをしているに違いありません。URL ファイルをアップロードすると、すべてピーチが動作します: http://imgur.com/sVH61.png
どのエンコーディングを使用すればよいのだろうか。:S