2

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

4

6 に答える 6

3

これを試して:

string file = @"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\Avatar.png";
string parameters = @"key=1df918979bf3f8dff2125c22834210903&image=" +
    Convert.ToBase64String(File.ReadAllBytes(file));
于 2010-01-11T18:44:13.933 に答える
3

マルチパート POST リクエストを正しく作成する必要があります。ここで例を参照してください: HTTPWebrequest を使用してファイルをアップロードする (multipart/form-data)

于 2010-01-11T19:59:22.000 に答える
1

API で投稿された画像を読む

public IHttpActionResult UpdatePhysicianImage(HttpRequestMessage request)
    {
        try
        {
            var form = HttpContext.Current.Request.Form;
            var model = JsonConvert.DeserializeObject<UserPic>(form["json"].ToString());
            bool istoken = _appdevice.GettokenID(model.DeviceId);
            if (!istoken)
            {
                statuscode = 0;
                message = ErrorMessage.TockenNotvalid;
                goto invalidtoken;
            }
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    // var filePath = uploadPath + postedFile.FileName;
                    //  string fileUrl = Utility.AbsolutePath("~/Data/User/" + model.UserId.ToString());
                    string fileUrl = Utility.AbsolutePath("~/" + Utility.UserDataFolder(model.UserId, "Document"));
                    if (!Directory.Exists(fileUrl))
                    {
                        Directory.CreateDirectory(fileUrl);
                        Directory.CreateDirectory(fileUrl + "\\" + "Document");
                        Directory.CreateDirectory(fileUrl + "\\" + "License");
                        Directory.CreateDirectory(fileUrl + "\\" + "Profile");
                    }
                    string imageUrl = postedFile.FileName;
                    string naviPath = Utility.ProfileImagePath(model.UserId, imageUrl);
                    var path = Utility.AbsolutePath("~/" + naviPath);
                    postedFile.SaveAs(path);
                    docfiles.Add(path);
                    if (model.RoleId == 2)
                    {
                        var doctorEntity = _doctorProfile.GetNameVideoChat(model.UserId);
                        doctorEntity.ProfileImagePath = naviPath;
                        _doctorProfile.UpdateDoctorUpdProfile(doctorEntity);
                    }
                    else
                    {
                        var patientEntity = _PatientProfile.GetPatientByUserProfileId(model.UserId);
                        patientEntity.TumbImagePath = naviPath;
                        _PatientProfile.UpdatePatient(patientEntity);
                    }
                }
                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
        catch (Exception e)
        {
            statuscode = 0;
            message = "Error" + e.Message;
        }
    invalidtoken:
        return Json(modeldata.GetData(statuscode, message));
    }
于 2015-10-17T07:11:59.093 に答える
0

jpgのコンテンツタイプをマルチパート境界に追加してみてください。

例については、このURLを参照してください(最後に)

http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

于 2010-01-11T19:10:38.590 に答える
0

変更してみてください:-

"application/x-www-form-urlencoded"

"multipart/form-data"
于 2010-01-11T18:42:11.687 に答える
-1

暗い場所で撮影しますが、おそらく Image のインスタンスを作成し、ファイルを Stream に保存し、それを使用してバイトを配列に読み取ってからアップロードします。

次のように:

Image i = System.Drawing.Image.FromFile("wut.jpg");
Stream stm = new Stream();
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameters paramz = new System.Drawing.Imaging.EncoderParameters(1);
myEncoderParameter = new EncoderParameter(myEncoder, 100L);
paramz.Param[0] = myEncoderParameter;
i.Save(stm, System.Drawing.Imaging.ImageFormat.Jpeg, paramz);
/* I'm lazy: code for reading Stream into byte[] here */
于 2010-01-12T16:26:35.220 に答える