使用 C# 和 WebRequest 上传图像?

发布于 2024-08-17 03:55:59 字数 2843 浏览 6 评论 0原文

这是 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 图像,我什么也得不到。例如: https://i.sstatic.net/8Y4uB.jpg

当我上传 PNG 时,上传的图片根本不显示。

我确定问题出在编码上。我能做些什么?

编辑 2!!!

现在我 100% 确定问题出在该方法的第一行。 File.ReadAllBytes() 一定做错了什么。如果我上传 URL 文件,则每个文件都可以正常工作: https://i.sstatic.net/clcmZ.png

我想知道我应该使用什么编码。 :S

Here is the working code in Python (using 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()

Here's what I have in 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");                  
        }            

    }

Now, the things I noticed is that when I changed my API key in the parameters string to "239231" or whatever number, the response I got was: "Invalid API key." So I think something must be working right.

I placed my correct API key and now I get a different response: "Invalid image format. Try uploading a JPEG image."

The service I'm using accepts almost every image format, so I am 100% certain the error is in the way I'm sending the file. Can anyone shed some light?

EDIT!!!

It turns out when I upload a JPG image I get that gray box thing. If I upload a big jpg image I don't get anything. For example: https://i.sstatic.net/8Y4uB.jpg

When I upload PNG's, the image uploaded doesn't even show.

I'm certain the issue is the encoding. What can I do?

EDIT 2!!!

Now I'm 100% certain that the problem lies in the first line of the method. The File.ReadAllBytes() must be doing something wrong. If I upload a URL file, every works peachy: https://i.sstatic.net/clcmZ.png

I wonder what encoding I should use. :S

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

画▽骨i 2024-08-24 03:55:59

试试这个:

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

Try this:

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));
今天小雨转甜 2024-08-24 03:55:59

您应该正确形成多部分 POST 请求。请参阅此处的示例:使用 HTTPWebrequest (multipart/form-data) 上传文件

You should correctly form a multipart POST request. See an example here: Upload files with HTTPWebrequest (multipart/form-data)

遗弃M 2024-08-24 03:55:59

读取 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));
    }

Read image posted by in 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));
    }
别忘他 2024-08-24 03:55:59

尝试更改 :-

"application/x-www-form-urlencoded"

"multipart/form-data"

Try changing :-

"application/x-www-form-urlencoded"

to

"multipart/form-data"
泅渡 2024-08-24 03:55:59

尝试将 jpg 的内容类型添加到多部分边界中。

请参阅此 URL 示例(在末尾)

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

Try adding the content-type for the jpg into your multipart boundary.

See this uRL for examples (at the end)

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

新一帅帅 2024-08-24 03:55:59

在黑暗中拍摄,但也许创建一个 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 */

Shot in the dark, but maybe create an instance of Image, save the file to a Stream and use that to read the bytes into an array then upload it.

As in:

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 */
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文