如何使用HttpWebRequest模拟浏览器文件上传

时间:2010-05-08 23:46:36

标签: c# httpwebrequest

伙计们,首先感谢您的贡献,我在这里找到了很好的回复。然而,我遇到了一个我无法弄清楚的问题,如果有人可以提供任何帮助,我将不胜感激。

我正在用C#开发这个应用程序,可以将图像从计算机上传到用户的photoblog。为此,我是用于主要用PHP编写的photoblogs的usig pixelpost 平台。

我在这里和其他网页上搜索过,但那里提供的例子对我没用。 这是我在我的例子中使用的:(Upload files with HTTPWebrequest (multipart/form-data)) 和 (http://bytes.com/topic/c-sharp/answers/268661-how-upload-file-via-c-code) 一旦准备就绪,我将在互联网上免费提供,也可以创建一个Windows移动版本,因为我是pixpost的粉丝。

这是我用过的代码:

        string formUrl = "http://localhost/pixelpost/admin/index.php?x=login";
        string formParams = string.Format("user={0}&password={1}", "user-String", "password-String");
        string cookieHeader;
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(formUrl);
        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";
        req.AllowAutoRedirect = false;
        byte[] bytes = Encoding.ASCII.GetBytes(formParams);
        req.ContentLength = bytes.Length;
        using (Stream os = req.GetRequestStream())
        {
            os.Write(bytes, 0, bytes.Length);
        }
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        cookieHeader = resp.Headers["Set-Cookie"];

        string pageSource;
        using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
        {
            pageSource = sr.ReadToEnd();
            Console.WriteLine();
        }

        string getUrl = "http://localhost/pixelpost/admin/index.php";
        HttpWebRequest getRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
        getRequest.Headers.Add("Cookie", cookieHeader);
        HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
        using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
        {
            pageSource = sr.ReadToEnd();
        }

        // end first part: login to admin panel

        long length = 0;
        string boundary = "----------------------------" +
        DateTime.Now.Ticks.ToString("x");

        HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/pixelpost/admin/index.php?x=save");
        httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
        httpWebRequest2.Method = "POST";
        httpWebRequest2.AllowAutoRedirect = false; 
        httpWebRequest2.KeepAlive = false;
        httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
        httpWebRequest2.Headers.Add("Cookie", cookieHeader);



        Stream memStream = new System.IO.MemoryStream();

        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");


        string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

        string formitem = string.Format(formdataTemplate, "headline", "image-name");
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        memStream.Write(formitembytes, 0, formitembytes.Length);

        memStream.Write(boundarybytes, 0, boundarybytes.Length);


        string headerTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";



        string header = string.Format(headerTemplate, "userfile", "path-to-the-local-file");

        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

        memStream.Write(headerbytes, 0, headerbytes.Length);


        FileStream fileStream = new FileStream("path-to-the-local-file", FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[1024];

        int bytesRead = 0;

        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            memStream.Write(buffer, 0, bytesRead);

        }

        memStream.Write(boundarybytes, 0, boundarybytes.Length);

        fileStream.Close();


        httpWebRequest2.ContentLength = memStream.Length;

        Stream requestStream = httpWebRequest2.GetRequestStream();

        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        memStream.Close();
        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        requestStream.Close();


        WebResponse webResponse2 = httpWebRequest2.GetResponse();

        Stream stream2 = webResponse2.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);


        Console.WriteLine(reader2.ReadToEnd());

        webResponse2.Close();
        httpWebRequest2 = null;
        webResponse2 = null;

这里也是PHP: (http://dl.dropbox.com/u/3149888/index.php) 和 (http://dl.dropbox.com/u/3149888/new_image.php

必填字段是标题 userfile 所以我无法弄清楚错误的位置,正如右边发送的格式一样。我猜测发送到表单的八位字节流有问题。 也许这是一个我无法追查的愚蠢错误,无论如何,如果你能帮助我,那将意味着很多。

感谢,

1 个答案:

答案 0 :(得分:5)

所以Martin帮助我在这里,我能够对上面的代码进行重要更改,以使其正常工作。 Content-Type必须更改为image / jpeg。我还使用C#Image类型发送图像流。

还要注意Stream格式,因为它不必包含额外的空格或新行。

这是改变的部分:

        string formUrl = "http://localhost/pixelpost/admin/index.php?x=login"; 
        string formParams = string.Format("user={0}&password={1}", "username", "password");
        string cookieHeader;
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(formUrl);
        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";
        req.AllowAutoRedirect = false;
        byte[] bytes = Encoding.ASCII.GetBytes(formParams);
        req.ContentLength = bytes.Length;
        using (Stream os = req.GetRequestStream())
        {
            os.Write(bytes, 0, bytes.Length);
        }
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        cookieHeader = resp.Headers["Set-Cookie"];

        string pageSource;
        using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
        {
            pageSource = sr.ReadToEnd();
        }

        string getUrl = "http://localhost/pixelpost/admin/index.php";
        HttpWebRequest getRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
        getRequest.Headers.Add("Cookie", cookieHeader);
        HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
        using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
        {
            pageSource = sr.ReadToEnd();
        }


        long length = 0;
        string boundary = "----------------------------" +
        DateTime.Now.Ticks.ToString("x");

        HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/pixelpost/admin/index.php?x=save");
        httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
        httpWebRequest2.Method = "POST";
        httpWebRequest2.AllowAutoRedirect = false;
        httpWebRequest2.KeepAlive = false;
        httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
        httpWebRequest2.Headers.Add("Cookie", cookieHeader);

        Stream memStream = new System.IO.MemoryStream();

        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary);


        string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: image/jpeg\r\n\r\n";



        string header = string.Format(headerTemplate, "userfile", "Sunset.jpg");



        byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(header);

        memStream.Write(headerbytes, 0, headerbytes.Length);


        Image img = null;
        img = Image.FromFile("C:/Documents and Settings/Dorin Cucicov/My Documents/My Pictures/Sunset.jpg", true);
        img.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg);


        memStream.Write(boundarybytes, 0, boundarybytes.Length);


        string formdataTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

        string formitem = string.Format(formdataTemplate, "headline", "Sunset");
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        memStream.Write(formitembytes, 0, formitembytes.Length);

        memStream.Write(boundarybytes, 0, boundarybytes.Length);


        httpWebRequest2.ContentLength = memStream.Length;

        Stream requestStream = httpWebRequest2.GetRequestStream();

        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        memStream.Close();
        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        requestStream.Close();


        WebResponse webResponse2 = httpWebRequest2.GetResponse();

        Stream stream2 = webResponse2.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);


        Console.WriteLine(reader2.ReadToEnd());

        webResponse2.Close();
        httpWebRequest2 = null;
        webResponse2 = null;

再次感谢大家回答或只是阅读。