gpt4 book ai didi

c# - 如何用HttpWebRequest模拟浏览器文件上传

转载 作者:太空狗 更新时间:2023-10-29 23:19:07 25 4
gpt4 key购买 nike

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

我正在用 C# 开发这个应用程序,它可以将图像从计算机上传到用户照片博客。为此,我使用 pixelpost 主要用 PHP 编写的照片博客平台。

我在这里和其他网页上搜索过,但那里提供的示例对我不起作用。这是我在示例中使用的内容:( Upload files with HTTPWebrequest (multipart/form-data) )和( http://bytes.com/topic/c-sharp/answers/268661-how-upload-file-via-c-code )一旦准备就绪,我将在 Internet 上免费提供它,并且可能还会创建它的 Windows 移动版本,因为我是 pixelpost 的粉丝。

这是我用过的代码:

        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 )

必填字段是headlineuserfile 所以我不知道错误在哪里,因为发送的格式是正确的。我猜发送到表单的八位字节流有问题。也许这是一个我无法追查的愚蠢错误,无论如何,如果你能帮助我,那将意义重大。

谢谢,

最佳答案

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

还要注意 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;

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

关于c# - 如何用HttpWebRequest模拟浏览器文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2796084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com