生成文件存储的虚拟路径:
private
static
string
GenerateVirtualFilePath()
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
Byte[] b = Guid.NewGuid().ToByteArray();
StringBuilder virtualFilePath = new StringBuilder();
for(Int32 i = 0; i < b.Length; i+=2)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Int32 folderName = b[i]*256 + b[i+1];
virtualFilePath.AppendFormat("{0}\\", folderName.ToString());
}
return virtualFilePath.ToString();
}
存储Client端上传的文件
public
static
string
Save(
string
saveRoot, HttpPostedFile entity)
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
string fileName = Path.GetFileName(entity.FileName);
string savePath = Path.Combine(saveRoot, GenerateVirtualFilePath());
if(!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
savePath = Path.Combine(savePath, fileName);
entity.SaveAs(savePath);
return savePath;
}
简单的替换字符串的操作,解决频繁的替换成Web访问路径
public
static
string
MapWebPath(
string
fileName,
string
saveRoot,
string
webRoot)
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
return fileName.Replace(saveRoot, webRoot);
}
将Post到客户端的函数
public
static
void
DownLoad(System.Web.UI.Page page,
string
filePath)
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
string fileName = Path.GetFileName(filePath);
fileName = HttpUtility.UrlPathEncode(fileName);
page.Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
page.Response.ContentType = "application/octet-stream";
page.Response.WriteFile(filePath);
page.Response.End();
}
验证文件类型
public
static
bool
ValidateFileType(
string
fileType,
string
fileExtention)
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
string[] fileTypeCollection = fileType.Split(',');
foreach(string type in fileTypeCollection)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(fileExtention.ToLower() == type.ToLower())
return true;
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
return false;
}