C#实现的文件上传下载工具类完整实例【上传文件自动命名】-创新互联
本文实例讲述了C#实现的文件上传下载工具类。分享给大家供大家参考,具体如下:

这里给出的工具类是在VS2013环境下采用C#语言实现文件上传、下载功能。上传时,为避免文件名在服务器中重复,采用“服务器时间+8位随机码+文件名+文件后缀“的方式作为服务器上的文件名;下载采用的是WebAPI的方式进行的,下载成功后可自定义文件的保存路径。
具体源码如下所示:
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using JYRS.Util;
namespace JYRS.Utils
{
public class FileHelper
{
///
/// 将文件名解析成文件的上传路径
///
/// 文件名
/// 文件路径
/// 文件在服务器上的路径
public static String transPath(string fileName, string path)
{
createDir(path);
//取服务器时间+8位随机码作为部分文件名,确保文件名无重复
string nowStr = DateTime.Now.ToString("yyyyMMddhhmmssff") + Global.CreateRandomCode(8);
// 去掉后缀的文件名
string fileNameStr = fileName.Substring(0, fileName.LastIndexOf("."));
// 文件后缀
String suffix = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (fileName.Trim() != "")
{
// 如果名称不为"",说明该文件存在,否则说明该文件不存在
path += "\\" + fileNameStr + nowStr + "." + suffix;// 定义上传路径
}
return path;
}
///
/// 创建文件目录
///
/// 根目录
///
private static void createDir(String root)
{
// 检查目录
if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(root)))
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(root));
}
}
///
/// 根据文件在服务器上的路径下载文件,此处采用的是WebAPI的方式进行文件下载,下载成功后可自定义文件的保存路径
///
/// 文件名
/// 文件路径
///
public static HttpResponseMessage download(string fileName, string path)
{
try
{
var stream = new FileStream(path, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
return response;
}
catch
{
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}
}
}
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
当前题目:C#实现的文件上传下载工具类完整实例【上传文件自动命名】-创新互联
本文地址:http://www.jxjierui.cn/article/epscc.html


咨询
建站咨询
