文件上傳時,如果使用的是原有文件名直接保存,而遇到服務器上有重名的情況,不能直接覆蓋原有文件,避免原有數據的丟失。
此時可以在上傳的文件名後面加上數字、隨機數或其他自定義字符串用以區別,附加信息和文件名之間用下劃線“_"分隔,便於識別文件的原始文件名。
以下代碼可以循環檢查文件名是否與服務器上的文件重名:
string upDirPhyPath = Server.MapPath("~/Upload");
HttpPostedFileBase file = Request.Files[0];
string fileName = Path.GetFileName(file.FileName), tmpFileName = fileName;
string fileExt = Path.GetExtension(fileName).ToLower();
int sameFileCount = 1;
if (file.ContentLength > 0)
{
while (System.IO.File.Exists(upDirPhyPath + "/" + tmpFileName))
{//文件名重複時後加一個數字
tmpFileName = fileName.Insert(fileName.LastIndexOf("."), "_" + sameFileCount);
sameFileCount++;
}
string filePath = Path.Combine(upDirPhyPath, tmpFileName);
file.SaveAs(filePath);
}