我有以下代码来在程序中上传附件。在此过程中,如果客户端在程序中上传的上传文件中选择了相同名称的文档,则必须向客户端发出更改文档名称的警告消息。
代码片段:
private string UploadFile()
{
string pathToSaveFile = Server.MapPath("~/Data/");
string clientFileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string upload_data = pathToSaveFile + clientFileName;
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.ContentLength > 0)
{
if (System.IO.File.Exists(upload_data))
{
//using Response.write
Response.Write(@"<script type='text/javascript'>alert('Rename it please.');</script>");
//ClientScriptManager
var clientScript = Page.ClientScript;
clientScript.RegisterClientScriptBlock(this.GetType(), "AlertScript", "alert('Rename it please.')'", true);
//ScriptManger
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", "alert('Member Registered Sucessfully');", true);
}
else
{
FileUpload1.PostedFile.SaveAs(System.IO.Path.Combine(pathToSaveFile, clientFileName));
}
}
else
{
Response.Write("Not Available");
}
return clientFileName;
}
我在程序中使用了各种 JavaScript 代码,但它们都不起作用。读码器只是读取代码并通过它。
当我提交表单按钮时,所有表单字段都会被读取并保存在一个对象中,当涉及到上传部分时,会读取上述代码,并将 clientFileName 传递给文件名对象并传递给 sqlquery将其输入数据库。
它不会为客户端显示任何更改文件名的警报弹出窗口。因此,相同的文件名被传递到服务器,并且由于相同的名称而引发冲突。
谢谢。
最佳答案
仅当您重新发布网站时才会弹出警报。 它无法在 C# 代码中运行。
参见下面的代码(仅供引用):
private bool UploadFile()
{
string pathToSaveFile = Server.MapPath("~/Data/");
string clientFileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string upload_data = pathToSaveFile + clientFileName;
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.ContentLength > 0)
{
if (System.IO.File.Exists(upload_data))
{
//using Response.write
Response.Write(@"<script type='text/javascript'>alert('Rename it please.');</script>");
//ClientScriptManager
var clientScript = Page.ClientScript;
clientScript.RegisterClientScriptBlock(this.GetType(), "AlertScript", "alert('Rename it please.')'", true);
//ScriptManger
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", "alert('Member Registered Sucessfully');", true);
return false;
}
else
{
FileUpload1.PostedFile.SaveAs(System.IO.Path.Combine(pathToSaveFile, clientFileName));
}
}
else
{
Response.Write("Not Available");
}
ViewState["FileName"] = clientFileName;
return true;
}
在函数外部使用如下内容:
if(UploadFile())
//run your SQL queue
else
return;//do all the return that will repost the website.
关于c# - Javascript 未在 C# 代码中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21665307/