【发布时间】:2016-12-01 13:04:20
【问题描述】:
使用 C# 中的这个 asp 网页上传文件,我需要检查重复项和文件扩展名。
我接受 3 个文件上传到服务器。
此代码有效,重复文件未上传,警报弹出窗口对所有发送上传的重复文件打开。
在服务器上上传前 3 个文件后,我尝试上传另一个扩展名为 .pdf 且服务器上存在一个 jpg 的文件。
对于扩展名为 .pdf 的文件,代码的响应是正确的
'仅 .jpg 或 .JPG 或 .png 扩展名'
第一个难度:
如何在此警报中添加扩展名为 .pdf 的文件名?
第二个难度:
对于服务器上存在的文件 jpg,响应代码不正确,因为还会警告同一服务器上存在另一个 jpg 文件。
例如在输出警报弹出窗口中只上传文件 IMG0002A.jpg:
- '文件IMG0002A.jpg存在'>>>正确
- '文件IMG0005A.jpg存在'>>>不正确
- '文件IMG0006A.jpg存在'>>>不正确
但我不发送上传文件:
- '文件IMG0005A.jpg存在'
- '文件IMG0006A.jpg存在'
有什么问题?
下面是我的代码,提前谢谢你。
if (FileExstention == ".jpg" || FileExstention == ".JPG" || FileExstention == ".png")
{
if (File.Exists(theFileName))
{
objDir = new DirectoryInfo(Server.MapPath("\\images\\);
objFI = objDir.GetFiles("*.*");
iFileCnt = 0;
if (objFI.Length > 0)
{
foreach (FileInfo file in objFI)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg" + iFileCnt, "alert('The file " + file.Name + " exists');", true);
iFileCnt += 1;
}
}
}
else
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
upload.SaveAs(directoryPath + "\\" + Path.GetFileName(theFileName));
}
else
{
upload.SaveAs(directoryPath + "\\" + Path.GetFileName(theFileName));
}
objDir = new DirectoryInfo(Server.MapPath("\\images\\);
objFI = objDir.GetFiles("*.*");
iFileCnt = 0;
if (objFI.Length > 0)
{
foreach (FileInfo file in objFI)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg" + iFileCnt, "alert('Saved file " + file.Name + ".');", true);
iFileCnt += 1;
}
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('Only .jpg or .JPG or .png exstention');", true);
}
编辑#1
if (objFI.Length > 0)
{
foreach (FileInfo file in objFI)
{
bool exists = file.Length > 0;
if (exists)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg" + iFileCnt, "alert('The file " + file.Name + " exists');", true);
iFileCnt += 1;
}
}
}
【问题讨论】: