Upload files to server _ C#
Using System
Using System.Collections.Generic
Using System.Linq
Using System.Text
Using System.Collections
Using System.Net
Using System.IO
Namespace www.xinduofen.cn
{
/ / /
/ C # tool class for interfacing with http server
/ / /
Class www.xinduofen.com
{
/ / /
/ / used to cache SESSIONID or JSESSIONID transferred from the server to the client
/ / /
Private Cookie sessionidCookie = null
/ / /
/ / upload files to HttpWebServer (using "post" method)
/ / /
/ / request URL
/ / request parameter collection. Null value is passed when no parameter is needed.
/ / request cookie collection. Pass a null value when no cookie is required.
/ / upload file collection "control name, the location where the upload file is saved (including" file name "." extension "). There is no need to pass a null value when uploading
/ / return the request result string, which means that the request failed if returned as null
Public String setFilesToHttpWebServer (String url, Hashtable data, CookieCollection cookies, Hashtable filesSaveAddress)
{
/ / used to cache the result string transmitted by the server
String result = null
If (string.IsNullOrEmpty (url))
{
Return null;// input parameter exception
}
/ / the delimiter used to split the information part (cannot conflict with the original message text)
String boundary = "HttpWebTool" + DateTime.Now.Ticks
/ / end delimiter data flow
Byte [] andBoundary = Encoding.UTF8.GetBytes ("-" + boundary + "-")
/ / New line string data stream
Byte [] newline = Encoding.UTF8.GetBytes ("\ r\ n")
Try
{
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create (url)
/ / request method
Req.Method = "POST"
/ / declare that the client only receives content of type txt
Req.Accept = "text/plain"
/ / pass parameters and data flow to the server in the form of a message
Req.ContentType = "multipart/form-data; boundary=" + boundary
/ / set the cookie box (the cookie requested by the client and the cookie returned by the server are placed in this box)
CookieContainer cookieContainer = new CookieContainer ()
If (sessionidCookie! = null & &! string.IsNullOrEmpty (sessionidCookie.Domain))
{
CookieContainer.Add (sessionidCookie)
}
If (cookies! = null)
{
CookieContainer.Add (cookies); / / add the cookie collection passed in by the caller
}
Req.CookieContainer = cookieContainer
/ / used to accumulate the length of the data stream, initialized to 0
Long dataCount = 0
Byte [] parameterBytes = getParameterBytes (data, boundary)
If (parameterBytes! = null & & parameterBytes.Length > 0)
{
/ / cumulative request parameter string data stream size
DataCount + = parameterBytes.Length
}
/ /
Hashtable uploadFileDeclareBytesSet = new Hashtable ()
/ / if there is a file to upload
If (filesSaveAddress! = null & & filesSaveAddress.Count > 0)
{
Foreach (DictionaryEntry de in filesSaveAddress)
{
/ / if the file to be uploaded exists
If (File.Exists (de.Value.ToString ()
{
Byte [] uploadFileDeclareBytes = getUploadFileDeclareBytes (de, boundary)
If (invalid adFileDeclareBytesNull)
{
/ / the header of the cumulative upload file describes the size of the string data stream
DataCount + = uploadFileDeclareBytes.Length
/ / cumulatively uploaded file body data stream size
DataCount + = new FileInfo (de.Value.ToString ()) .Length
/ / accumulate new line string data stream size
DataCount + = newline.Length
UploadFileDeclareBytesSet.Add (de.Key.ToString (), uploadFileDeclareBytes)
}
}
}
}
/ / if there is a data stream
If (dataCount > 0)
{
/ / cumulative end delimiter data flow size
DataCount + = andBoundary.Length
/ / request the length of the data stream
Req.ContentLength = dataCount
Using (Stream requestStream = req.GetRequestStream ())
{
If (parameterBytes! = null & & parameterBytes.Length > 0)
{
RequestStream.Write (parameterBytes, 0, parameterBytes.Length)
}
If (filesSaveAddress! = null & & filesSaveAddress.Count > 0)
{
Foreach (DictionaryEntry de in filesSaveAddress)
{
If (File.Exists (de.Value.ToString ()
{
Byte [] uploadFileDeclareBytes = (byte []) uploadFileDeclareBytesSet [de.Key.ToString ()]
RequestStream.Write (uploadFileDeclareBytes, 0, uploadFileDeclareBytes.Length)
Using (FileStream fileStream = new FileStream (de.Value.ToString (), FileMode.Open, FileAccess.Read))
{
/ / establish a byte group and set its size to how many bytes
Byte [] bytes = new byte [10240]
Int n =-1
While ((n = fileStream.Read (bytes, 0, bytes.Length)) > 0)
{
RequestStream.Write (bytes, 0, n); / / writes the specified byte of stream information to the file stream
}
}
RequestStream.Write (newline, 0, newline.Length)
}
}
}
RequestStream.Write (andBoundary, 0, andBoundary.Length)
}
}
/ / receive the return value
Using (HttpWebResponse myResponse = (HttpWebResponse) req.GetResponse ()) {
Using (StreamReader reader = new StreamReader (myResponse.GetResponseStream (), Encoding.UTF8)) {
Result = reader.ReadToEnd () .Trim ()
}
If (myResponse.Cookies ["SESSIONID"]! = null)
{
SessionidCookie = myResponse.Cookies ["SESSIONID"]
}
Else
{
If (myResponse.Cookies ["JSESSIONID"]! = null)
{
SessionidCookie = myResponse.Cookies ["JSESSIONID"]
}
}
}
}
Catch (Exception)
{
Console.WriteLine ("Please check whether the incoming parameters are correct or whether the server is down")
}
Return result
}
/ / /
/ / get the message data flow for the parameter data, ending with "\ r\ n"
/ / /
/ / request parameter collection. Null value is passed when no parameter is needed.
/ / message delimiter
/ / return the data flow of the parameter data. If it is empty, it means the acquisition failed.
Private byte [] getParameterBytes (Hashtable data, String boundary)
{
Byte [] parameterBytes = null
/ / if there are request parameters
If (data! = null & & data.Count > 0)
{
String parameterStr = ""
Foreach (DictionaryEntry de in data)
{
ParameterStr + = "-" + boundary
ParameterStr + = "\ r\ n" + "Content-Disposition: form-data;name=\"+ de.Key.ToString () +"\ ""
ParameterStr + = "\ r\ n" + "Content-Type: text/plain; charset=UTF-8"
ParameterStr + = "\ r\ n\ r\ n" + de.Value.ToString ()
ParameterStr + = "\ r\ n"
}
If (! string.IsNullOrEmpty (parameterStr))
{
ParameterBytes = Encoding.UTF8.GetBytes (parameterStr); / / package uploaded string data into a data stream
}
}
Return parameterBytes
}
/ / /
/ / get the header character stream of the uploaded file, ending with "\ r\ n\ r\ n"
/ / /
/ / upload file "control name, location where the uploaded file is saved (including" file name "." extension ")"
/ / message delimiter
/ / return the character stream of the header part of the uploaded file. The return will fail for the null representative.
Private byte [] getUploadFileDeclareBytes (DictionaryEntry de, String boundary)
{
Byte [] uploadFileDeclareBytes = null
/ / the header description part of the uploaded file
String uploadFileDeclareStr = ""
UploadFileDeclareStr + = "-" + boundary
UploadFileDeclareStr + = "\ r\ n" + "Content-Disposition: form-data;name=\"+ de.Key.ToString () +"\ "; filename=\"+ de.Value.ToString () +"\ ""
UploadFileDeclareStr + = "\ r\ n" + "Content-Type: application/octet-stream"
UploadFileDeclareStr + = "\ r\ n\ r\ n"
If (! string.IsNullOrEmpty (uploadFileDeclareStr))
{
UploadFileDeclareBytes = Encoding.UTF8.GetBytes (uploadFileDeclareStr); / / package uploaded string data into a data stream
}
Return uploadFileDeclareBytes
}
}
}
The ownership of the content belongs to Yuekang Sports (specializing in physique tester, student physique tester research)