文件上传时,如果使用的是原有文件名直接保存,而遇到服务器上有重名的情况,不能直接覆盖原有文件,避免原有数据的丢失。
此时可以在上传的文件名后面加上数字、随机数或其他自定义字符串用以区别,附加信息和文件名之间用下划线“_"分隔,便于识别文件的原始文件名。
以下代码可以循环检查文件名是否与服务器上的文件重名:
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);
}