C#实现的文件上传下载工具类完整实例【上传文件自动命名】
本文实例讲述了C#实现的文件上传下载工具类。分享给大家供大家参考,具体如下:
这里给出的工具类是在VS2013环境下采用C#语言实现文件上传、下载功能。上传时,为避免文件名在服务器中重复,采用“服务器时间+8位随机码+文件名+文件后缀“的方式作为服务器上的文件名;下载采用的是WebAPI的方式进行的,下载成功后可自定义文件的保存路径。
具体源码如下所示:
usingSystem;
usingSystem.IO;
usingSystem.Net;
usingSystem.Net.Http;
usingSystem.Net.Http.Headers;
usingJYRS.Util;
namespaceJYRS.Utils
{
publicclassFileHelper
{
///
///将文件名解析成文件的上传路径
///
///文件名
///文件路径
///文件在服务器上的路径
publicstaticStringtransPath(stringfileName,stringpath)
{
createDir(path);
//取服务器时间+8位随机码作为部分文件名,确保文件名无重复
stringnowStr=DateTime.Now.ToString("yyyyMMddhhmmssff")+Global.CreateRandomCode(8);
//去掉后缀的文件名
stringfileNameStr=fileName.Substring(0,fileName.LastIndexOf("."));
//文件后缀
Stringsuffix=fileName.Substring(fileName.LastIndexOf(".")+1);
if(fileName.Trim()!="")
{
//如果名称不为"",说明该文件存在,否则说明该文件不存在
path+="\\"+fileNameStr+nowStr+"."+suffix;//定义上传路径
}
returnpath;
}
///
///创建文件目录
///
///根目录
///
privatestaticvoidcreateDir(Stringroot)
{
//检查目录
if(!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(root)))
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(root));
}
}
///
///根据文件在服务器上的路径下载文件,此处采用的是WebAPI的方式进行文件下载,下载成功后可自定义文件的保存路径
///
///文件名
///文件路径
///
publicstaticHttpResponseMessagedownload(stringfileName,stringpath)
{
try
{
varstream=newFileStream(path,FileMode.Open);
HttpResponseMessageresponse=newHttpResponseMessage(HttpStatusCode.OK);
response.Content=newStreamContent(stream);
response.Content.Headers.ContentType=newMediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition=newContentDispositionHeaderValue("attachment")
{
FileName=fileName
};
returnresponse;
}
catch
{
returnnewHttpResponseMessage(HttpStatusCode.NoContent);
}
}
}
}
Controller层调用类
[HttpGet]
publicHttpResponseMessageUploadAndDownload()
{
//文件上传到服务器上的根目录
stringroot=System.Web.Hosting.HostingEnvironment.MapPath(@"~/upload");
stringfileName="测试.docx";
//解析文件在服务器上的上传路径
stringpath=FileHelper.transPath(fileName,root);
//获取要上传的文件
varfiles=HttpContext.Current.Request.Files;
HttpPostedFilefile=HttpContext.Current.Request.Files[0];
//保存文件
file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
//下载word文件
returnFileHelper.download(fileName,path);
}
view层:
导出
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#文件操作常用技巧汇总》、《C#遍历算法与技巧总结》、《C#程序设计之线程使用技巧总结》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》及《C#面向对象程序设计入门教程》
希望本文所述对大家C#程序设计有所帮助。