Skip to content

Instantly share code, notes, and snippets.

@robinli
Last active December 21, 2015 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinli/6274401 to your computer and use it in GitHub Desktop.
Save robinli/6274401 to your computer and use it in GitHub Desktop.
非網頁的程式,將檔案上傳至 Web 端
/// <summary>
/// source from http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data
/// </summary>
/// <param name="url"></param>
/// <param name="files"></param>
/// <param name="nvc">POST data, if nothing then set null</param>
/// <returns></returns>
public static string UploadFilesToRemoteUrl(string url, FileInfo[] files, NameValueCollection nvc)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials =
System.Net.CredentialCache.DefaultCredentials;
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}";
if (nvc != null)
{
foreach (string key in nvc.Keys)
{
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
foreach(FileInfo fi in files)
{
string header = string.Format(headerTemplate, fi.Name, fi.Name);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(fi.FullName, 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);
string result = reader2.ReadToEnd();
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
return result;
}
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
string UploadServerPath = context.Server.MapPath("Upload");
int loop1;
HttpFileCollection Files = context.Request.Files; // Load File collection into HttpFileCollection variable.
string[] arr1 = Files.AllKeys; // This will get names of all files into a string array.
for (loop1 = 0; loop1 < arr1.Length; loop1++)
{
context.Response.Write("File: " + context.Server.HtmlEncode(arr1[loop1]) + "<br />");
context.Response.Write(" size = " + Files[loop1].ContentLength + "<br />");
context.Response.Write(" content type = " + Files[loop1].ContentType + "<br />");
Files[loop1].SaveAs(
Path.Combine(UploadServerPath, Path.GetFileName(Files[loop1].FileName))
);
}
context.Response.Write(string.Format("has upload {0} file.<br />" , arr1.Length));
//POST data
foreach (string key in context.Request.Form.AllKeys)
{
context.Response.Write(string.Format("{0}={1}<br />", key, context.Request.Form[key]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment