热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

C#上传文件

#region文件上传上传文件

#region 文件上传
///


/// 上传文件
///

///


///


///


///
public static HttpWebResponse CreatePostUploadFileResponse(string url, string filePath, IDictionary parameters = null, int timeout = 30000, Encoding requestEncoding = null)
{
if (requestEncoding == null)
{
requestEncoding = System.Text.Encoding.UTF8;
}
var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.COntentType= "multipart/form-data; boundary=" + boundary;
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "*/*";
httpWebRequest.KeepAlive = true;
httpWebRequest.Timeout = timeout;
httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
HttpWebResponse reponse;
var stream = httpWebRequest.GetRequestStream();
var formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
//添加其他参数
if (!(parameters == null || parameters.Count == 0))
{
foreach (string key in parameters.Keys)
{
string formitem = string.Format(formdataTemplate, key, parameters[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
stream.Write(formitembytes, 0, formitembytes.Length);
}
}
stream.Write(boundarybytes, 0, boundarybytes.Length);
var fileName = Path.GetFileName(filePath);
var extension = Path.GetExtension(fileName);
var headerTemplate = "Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";
string header = string.Format(headerTemplate, fileName, GetContentType(extension));
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
stream.Write(headerbytes, 0, headerbytes.Length);
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
stream.Write(trailer, 0, trailer.Length);
stream.Close();
//成功回傳結果
repOnse= httpWebRequest.GetResponse() as HttpWebResponse;
return reponse;
}

///


/// 上传文件
///

///


///


///


///
public static HttpWebResponse CreatePostUploadFileResponse(string url, string fileName, MemoryStream fileStream, IDictionary parameters = null, int timeout = 30000, Encoding requestEncoding = null)
{
if (requestEncoding == null)
{
requestEncoding = System.Text.Encoding.UTF8;
}
var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.COntentType= "multipart/form-data; boundary=" + boundary;
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "*/*";
httpWebRequest.KeepAlive = true;
httpWebRequest.Timeout = timeout;
httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
HttpWebResponse reponse;
var stream = httpWebRequest.GetRequestStream();
var formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
//添加其他参数
if (!(parameters == null || parameters.Count == 0))
{
foreach (string key in parameters.Keys)
{
string formitem = string.Format(formdataTemplate, key, parameters[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
stream.Write(formitembytes, 0, formitembytes.Length);
}
}
stream.Write(boundarybytes, 0, boundarybytes.Length);
var extension = Path.GetExtension(fileName);
var headerTemplate = "Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";
string header = string.Format(headerTemplate, fileName, GetContentType(extension));
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
stream.Write(headerbytes, 0, headerbytes.Length);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
stream.Write(trailer, 0, trailer.Length);
stream.Close();
//成功回傳結果
repOnse= httpWebRequest.GetResponse() as HttpWebResponse;
return reponse;
}
///


///
///

///


///
public static string GetContentType(string fileExtension)
{
var mimeTypes = new Dictionary
{
{".bmp", "image/bmp"},
{".gif", "image/gif"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".png", "image/png"},
{".tif", "image/tiff"},
{".tiff", "image/tiff"},
{".doc", "application/msword"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".pdf", "application/pdf"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xls", "application/vnd.ms-excel"},
{".csv", "text/csv"},
{".xml", "text/xml"},
{".txt", "text/plain"},
{".zip", "application/zip"},
{".ogg", "application/ogg"},
{".mp3", "audio/mpeg"},
{".wma", "audio/x-ms-wma"},
{".wav", "audio/x-wav"},
{".wmv", "audio/x-ms-wmv"},
{".swf", "application/x-shockwave-flash"},
{".avi", "video/avi"},
{".mp4", "video/mp4"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".qt", "video/quicktime"}
};
// if the file type is not recognized, return "application/octet-stream" so the browser will simply download it
return mimeTypes.ContainsKey(fileExtension) ? mimeTypes[fileExtension] : "application/octet-stream";
}
#endregion
View Code

 



推荐阅读
author-avatar
不会做饭的我
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有