我在asp.net mvc中使用HttpWebRequest
自动执行http post的过程。
基本上如果Http帖子成功,它会将所有post值写入数据库或文件。
它适用于简单类型,如strings,int,datetime。但我不确定如何从图像或其他文件(如.doc
,.pdf
...
手动上传文件时,文件的输入值为UploadedFile:****.JPG
;选择本地文件后,我可以做http帖子
string mimeType = Request.Files[upload].ContentType;
Stream fileStream = Request.Files[upload].InputStream;
string fileName = Path.GetFileName(Request.Files[upload].FileName);
int fileLength = Request.Files[upload].ContentLength;
byte[] fileData = new byte[fileLength];
fileStream.Read(fileData, 0, fileLength);
...
但我正在进行自动化,所以我想我需要一个类似field1=value1&field2=value2&UploadedFile=****.JPG
的查询字符串;但我认为该过程不起作用,因为网页不知道图像在哪里。那么任何想法使用一个神奇的Url来定位图像或任何文件,以便我可以将它转换为字节数组并操纵它?
答案 0 :(得分:1)
您可以使用base64编码将二进制数据转换为字符串,然后将其放入查询字符串中,但不建议这样做。对于发送二进制数据,最好在http请求中使用post方法及其数据。
和代码:
public void PostMultipleFiles(string url, string[] files)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
using(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 headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
memStream.Write(boundarybytes, 0, boundarybytes.Length);
for (int i = 0; i < files.Length; i++)
{
string header = string.Format(headerTemplate, "file" + i, files[i]);
//string header = string.Format(headerTemplate, "uplTheFile", files[i]);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
using(FileStream fileStream = new FileStream(files[i], 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);
}
}
httpWebRequest.ContentLength = memStream.Length;
using(Stream requestStream = httpWebRequest.GetRequestStream())
{
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
}
}
try
{
WebResponse webResponse = httpWebRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string var = reader.ReadToEnd();
}
catch (Exception ex)
{
// ...
}
}