使用 C# 和 WebRequest 上传图像? [英] Uploading an image using C# and WebRequest?

查看:45
本文介绍了使用 C# 和 WebRequest 上传图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 Python 中的工作代码(使用 cURL):

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

这是我在 C# 中的内容:

Here's what I have in 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 密钥".所以我认为某些事情一定是正确的.

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.

我放置了我的正确 API 密钥,现在我得到了不同的响应:图像格式无效.尝试上传 JPEG 图像."

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

我使用的服务几乎接受所有图像格式,因此我 100% 确定错误在于我发送文件的方式.任何人都可以透露一些信息吗?

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?

编辑!!!

事实证明,当我上传 JPG 图像时,我得到了那个灰色框的东西.如果我上传一个大的 jpg 图片,我什么也得不到.例如:http://i.imgur.com/gFsUY.jpg

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: http://i.imgur.com/gFsUY.jpg

当我上传 PNG 文件时,上传的图片甚至不显示.

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

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

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

编辑 2!!!

现在我 100% 确定问题出在方法的第一行.File.ReadAllBytes() 一定是做错了什么.如果我上传一个 URL 文件,每一个都可以正常工作:http://imgur.com/sVH61.png

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: http://imgur.com/sVH61.png

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

I wonder what encoding I should use. :S

推荐答案

试试这个:

string file = @"C:UsersSergiodocumentsvisual studio 2010ProjectsWpfApplication1WpfApplication1TestAvatar.png";
string parameters = @"key=1df918979bf3f8dff2125c22834210903&image=" +
    Convert.ToBase64String(File.ReadAllBytes(file));

这篇关于使用 C# 和 WebRequest 上传图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆