Загрузка изображения с помощью C# и WebRequest?



Вот рабочий код на 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:UsersSergiodocumentsvisual studio 2010ProjectsWpfApplication1WpfApplication1Testhotness2.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% уверен, что проблема заключается в первой строке метода. файл.ReadAllBytes() должно быть делает что-то не так. Если я загружаю URL-файл, каждый работает peachy: http://imgur.com/sVH61.png

Интересно, какую кодировку мне следует использовать. :S

682   6  

6 ответов:

Попробуйте это:

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

Вы должны правильно сформировать многострочный запрос POST. Смотрите пример здесь: Загрузка файлов с помощью HTTPWebrequest (multipart/form-data)

Прочитать изображение, опубликованное в 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));
    }

Попробуйте изменить : -

"application/x-www-form-urlencoded"

К

"multipart/form-data"

Попробуйте добавить тип содержимого для jpg в вашу составную границу.

Смотрите этот uRL для примеров (в конце)

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

Снимок в темноте, но, возможно, создать экземпляр изображения, сохранить файл в поток и использовать его для чтения байтов в массив, а затем загрузить его.

Как в:

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 */

Comments

    Ничего не найдено.