0

I am automating the process of http post using HttpWebRequest in asp.net mvc.

Basically if the Http post is successful, it will write all the post value into a database or a file.

It works well with simple types such as strings,int, datetime. But I am not sure how to create a query string from a image,or other files such as .doc,.pdf...

When doing a file upload manually, the input value of the file will be UploadedFile:****.JPG; After choosing a local file ,for the http post I can do

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

But I am doing the automating so I guess I need a query string something like field1=value1&field2=value2&UploadedFile=****.JPG;But I think the process won't work as the web page had no idea where the image is. So any ideas to use a phicical Url to locate the image or any file so that I can convert it to byte array and manipulate it ?

baozi
  • 679
  • 10
  • 30

1 Answers1

1

You can use base64 encoding to convert binary data to string and then put it in your query string, but its not recommended. For sending binary data its better to use post method and its data in your http request.

like this, or ^, ^, ^.

and the code:

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)
    {
        // ...
    }
}
Community
  • 1
  • 1