c# - 使用 C# 和 WebRequest 上传图像?

标签 c# post httpwebrequest 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:\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 key 更改为“239231”或任何数字时,我得到的响应是:“无效的 API key ”。所以我认为一定有什么东西在正常工作。

我放置了我的正确 API key ,现在我收到了不同的响应:“无效的图像格式。尝试上传 JPEG 图像。”

我使用的服务几乎接受所有图像格式,因此我 100% 确定错误出在我发送文件的方式上。任何人都可以解释一下吗?

编辑!!!

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

当我上传 PNG 时,上传的图像甚至不显示。

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

编辑 2!!!

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

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

最佳答案

试试这个:

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

关于c# - 使用 C# 和 WebRequest 上传图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2043997/

相关文章:

c# - SecurityPermission 和 SecurityPermissionFlag.SkipVerification 的后果

c# - 通过 ASP.NET 代码隐藏下载文件时如何强制 Chrome 打开 "open file dialog"?

php - 从表单将数据发送到 SQL 数据库时出错

html - 使 href( anchor 标记)请求 POST 而不是 GET?

http - 配置 HTTP Post header 和正文以发送 Twilio 请求

java - C# 和 Java 之间的不同内容长度

c# - 多个中间件(REST + SOAP)

c# - HttpContext 用户声明为空

asp.net - HTTPWebRequest "PUT"错误状态 405 IIS7 中不允许的方法

c# - HttpWebRequest 日期 header 格式