本文属于个人原创作品、个人总结,谢绝转载、抄袭。如果您有疑问或者希望沟通交流,可以联系QQ:865562060。
1、aspx页面使用file选择文件
后台获取文件并读取成字节组
files = file.FileName.Split('\\');
//filename = files[files.Length - 1];
string[] sArray = files[files.Length - 1].Split('.');
filename = sArray[0];
fileType = sArray[1];
//接收上传文件
Stream fileStream = file.InputStream;
//获取上传文件字节的大小
int length = file.ContentLength;
byte[] Data = new byte[length];
//从流中读取字节并写入wordData
fileStream.Read(Data, 0, length);
获取文件字节组之后,可以选择不同文件储存方案。例如:1、将字节组存储在数据库表中;2、将文件读取存储到应用服务器指定路径,并在数据库保存存储路径;3、将文件读取存储到文件服务器,文件服务器可以不与应用服务器统一(通过接口实现文件存储读取)。
2、文件存储至应用服务器(一般处理方式)。
//生成上传文件目录
string uploadPath = HttpContext.Current.Server.MapPath(@"\UpLoaderFiles");
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
FileStream pFileStream = null;
string fileName = filename + "." + fileType;
string pre = DateTime.Now.ToString("yyyyMMddHHssmm") + new Random().Next(10000);
fileName = pre + "_" + fileName;
string AttPath = uploadPath + "\\" + fileName;
pFileStream = new FileStream(AttPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
pFileStream.Write(Data, 0, Data.Length);
pFileStream.Close();
3、文件存储于文件服务器(推荐处理方式)。(这里demo使用第三方程序,企捷微信协同办公平台。安装简单,形成文件服务器和接口路径,直接调用即可。地址:http://qjkj.mydoc.io/?t=290541)
//使用企捷微信协同办公平台POST接口上传文件
HttpWebRequest request2 = WebRequest.Create(url) as HttpWebRequest;//url为文件服务器接口地址
CookieContainer cookieContainer = new CookieContainer();
request2.CookieContainer = cookieContainer;
request2.AllowAutoRedirect = true;
request2.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request2.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
Stream postStream = request2.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
//写入文件
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n", filename, filename + "." + fileType));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(Data, 0, Data.Length);
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); //结束标志
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse response2 = request2.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream instream = response2.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
4、文件存储至数据库表(不推荐)。
将字节组Data直接存储于数据库表字段中,使用时直接将字节组读取成文件。这样会对IO造成一定的压力。
1、针对网络路径文件,使用http,读文件响应流的方式。
//设置参数
HttpWebRequest request = WebRequest.Create(filePath) as HttpWebRequest;
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = response.GetResponseStream();
byte[] byteFile = null;
List bytes = new List();
int temp = responseStream.ReadByte();
while (temp != -1)
{
bytes.Add((byte)temp);
temp = responseStream.ReadByte();
}
byteFile = bytes.ToArray();
response.Close();
responseStream.Close();
fileName = fileName + "." + filetype;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.BinaryWrite(byteFile);
HttpContext.Current.Response.End();
2、针对应用服务器本地文件,通过FileStream读取文件在缓存中输出,io只能对本地路径有用,网络路径无法使用这种方式。
//文件在本地,通过FileStream读取文件在缓存中输出
FileStream pFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] bytes = new byte[pFileStream.Length];
pFileStream.Read(bytes, 0, (int)pFileStream.Length);
MemoryStream ms = new MemoryStream(bytes);
fileName = fileName + "." + filetype;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
ms.Close();
HttpContext.Current.Response.End();
C#实现文件上传下载比较简单,将文件转换字节组再进行读写操作。需要注意的本地文件和网络文件的读取方式不同,另外应用服务器或者文件服务器上存储文件夹对于用户的操作权限也需要分配好。