1.基本信息
a.文件名
fileName="程序员周加班清单.xlsx";
b.上传的文件都存在此目录下
everFolder="~/Upload/";
c.上传的文件存在Upload目录下的文件夹,或通过传值,或其他
downLoadFolder=context.Request.Form["DownLoadFolder"];
2.获取文件夹虚拟路径
public string GetRelativePath(HttpContext context)
{
string fileFolder = string.IsNullOrEmpty(
context.Request.QueryString["DownLoadFolder"]) ?
context.Request.Form["DownLoadFolder"] :
context.Request.QueryString["DownLoadFolder"];
string path = "~/Upload/";
if (!string.IsNullOrEmpty(fileFolder.Trim()))
{
path = Path.Combine(path, fileFolder);
}
//保证其路径的正确,匹配{\|/},用DirectorySeparatorChar{\}替换
//可以不用写
Regex r = new Regex("\\|/", RegexOptions.None);
path = r.Replace(path, Path.DirectorySeparatorChar.ToString());
return path;
}
我这里执行的结果结果:"~/Upload/PROOther"
3.将"~/Upload/PROOther"
转换为绝对路径,并判断其文件夹是否存在,不存在就创建。
private static string BuildPath(string path)
{
//如果有path就转换为绝对路径
if (!Path.IsPathRooted(path))
{
path = HttpContext.Current.Server.MapPath(path);
}
//如果没有`"~/Upload/PROOther"`这个文件夹就创建
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return Path.GetFullPath(path);
}
执行结果:
"D:\\TFS\\Demo\\Demo.Website\\Upload\\PROOther"
3.用日期+GUID为文件命名
path:为2的结果;fileName:为1中文件名。
private string GetRenewName(string path, string fileName)
{
string strFullPath = string.Empty;
string strNewName = fileName;
//文件名,不含后缀
string fileNameNoExt = fileName;
//文件后缀名,包含“.”
string fileExtension = string.Empty;
int i = fileName.LastIndexOf('.');
if (i > 0)
{
//文件名,不含后缀,Substring截取时不包括endindex,此处不需减1
fileNameNoExt = fileName.Substring(0, i);
//文件后缀
fileExtension = fileName.Substring(i, fileName.Length - i);
}
//用GUID作为文件名
strNewName = string.Format("{0}_{1}{2}",
DateTime.Now.ToString("yyyy-MM-dd"),
Guid.NewGuid(), fileExtension);
return strNewName;
}
结果:
"2017-07-26_ebd1c686-9ce2-4850-af38-8b74a9cca7ad.xlsx"
4.虚拟文件路径,绝对文件路径
relativeFilePath = Path.Combine(relativePath, strNewFileName);
结果:"~/Upload/PROOther\\2017-07-26_ebd1c686-9ce2-4850-af38-8b74a9cca7ad.xlsx"
clientFilePath = VirtualPathUtility.ToAbsolute(relativeFilePath);
结果:"~/Upload/PROOther/2017-07-26_ebd1c686-9ce2-4850-af38-8b74a9cca7ad.xlsx"
5.文件全路径
fullPath:”D:\TFS\Demo\Demo.Website\Upload\PROOther”
destFile = Path.Combine(fullPath, strNewFileName);
结果:
"D:\\TFS\\Demo\\Demo.Website\\Upload\\PROOther\\2017-07-26_ebd1c686-9ce2-4850-af38-8b74a9cca7ad.xlsx"
6.保存
我这里用的是ashx.cs保存
HttpPostedFile hpfFile = context.Request.Files[0];
hpfFile.SaveAs(destFile);
以上有些步骤是不需要的!如有错误,请留言偏于改正,谢谢!