在做论坛的时候经常会遇到客户上传文件后,没有提交,那么文件就会遗留在服务器上,当然有另外的解决办法,今天我给出一种方法来使得用户离开页面之后如果未提交的话会自动删除上传文件.原理很简单,就是当用户离开的时候触发onbeforeunload事件,然后利用客户端回调删除服务端数据.
我把上传页面放在单独的一个iframe里面PostMessage.aspx:


1
public partial class PostMessage : System.Web.UI.Page
2

{
3
protected void Page_Load(object sender, EventArgs e)
4
{
5
this.lbuploaderror.Text = "";
6
7
}
8
protected void btnUpload_Click(object sender, EventArgs e)
9
{
10
string htmlpath="http://" +Context.Request.Url.Host + Context.Request.ApplicationPath ;
11
if (this.FileUpload1.PostedFile.FileName.ToString() == "")
12
{
13
this.lbuploaderror.Text = "Please select a file to upload!";
14
return;
15
}
16
try
17
{
18
if (this.FileUpload1.PostedFile.FileName.ToString() != "")
19
{
20
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
21
AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
22
string sPath =Server.MapPath(appSection.Settings["UploadFilePath"].Value.ToString());
23
24
25
string savename = DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString()+DateTime.Now.Day.ToString()+DateTime.Now.Hour.ToString()+DateTime.Now.Minute.ToString()+DateTime.Now.Second.ToString()+DateTime.Now.Millisecond.ToString()+ "." + this.FileUpload1.PostedFile.FileName.Substring(this.FileUpload1.PostedFile.FileName.LastIndexOf(".") + 1);
26
27
if (this.FileUpload1.PostedFile != null && this.FileUpload1.PostedFile.FileName.Substring(this.FileUpload1.PostedFile.FileName.IndexOf(".") + 1) != "")
28
{
29
if (this.FileUpload1.PostedFile.FileName.ToLower().IndexOf("gif") < 0 && this.FileUpload1.PostedFile.FileName.ToLower().IndexOf("jpg") < 0 && this.FileUpload1.PostedFile.FileName.ToLower().IndexOf("jpeg") < 0 && this.FileUpload1.PostedFile.FileName.ToLower().IndexOf("bmp") < 0 && this.FileUpload1.PostedFile.FileName.IndexOf("rar") < 0 && this.FileUpload1.PostedFile.FileName.ToLower().IndexOf("png") < 0 && this.FileUpload1.PostedFile.FileName.ToLower().IndexOf("zip")<0)
30
{
31
Page.RegisterStartupScript("", "<script language='JavaScript'>alert('Only these file(*.png;*.gif;*.jpg;*.bmp;*.jpeg,*.rar,*.zip) allowed!');</script>");
32
return;
33
}/**////End of if
34
if (this.FileUpload1.PostedFile.ContentLength > 200000)
35
{
36
37
Page.RegisterStartupScript("", "<script language='JavaScript'>alert('Picture file should no more than 200k!');</script>");
38
return;
39
}/**////End of if
40
// string sPath = uploadFolder;
41
try
42
{
43
this.FileUpload1.PostedFile.SaveAs(sPath + savename);
44
if (savename.ToLower().IndexOf("rar") > 0 || savename.ToLower().IndexOf("zip") > 0)
45
{
46
this.FreeTextBox1.Text += "<a href='" + htmlpath + "/" + appSection.Settings["UploadFilePath"].Value.ToString().Substring(2) + savename + "'>"+savename+"</a>";
47
}
48
else this.FreeTextBox1.Text += "<img src='" + htmlpath+"/" + appSection.Settings["UploadFilePath"].Value.ToString().Substring(2) +savename+"'/>";
49
if (Session["upload"] == null) Session["upload"] = savename;
50
else Session["upload"] += "," + savename;
51
Session["unsave"] = "yes";
52
}
53
catch
54
{
55
Page.RegisterStartupScript("", "<script language='JavaScript'>alert('Upload picture failed');</script>");
56
return;
57
}
58
}/**////End of if
59
}
60
}
61
catch
62
{
63
64
Page.RegisterStartupScript("", "<script language='JavaScript'>alert('Upload picture failed');</script>");
65
return;
66
}
67
}
主页面的页面文件:


1
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
2
<script>
function deletefile()
{
3
DeleteFile();
4
}
5
function ClientCallback(result,context)
{
6
alert(result);
7
}
8
function ClientErrorCallback(error,context)
{
9
alert(error);
10
}
11
function document.body.onbeforeunload()
{
12
deletefile();
13
}
14
</script>
15
<div style=" width:100%"><iframe width=100% height=100% frameborder =no src="PostMessage.aspx"></iframe></div>
16
</asp:Content>
17
后台代码:


1
public partial class Forum_Detail : System.Web.UI.Page,ICallbackEventHandler
2

{
3
string _returnvalue="";
4
protected void Page_Load(object sender, EventArgs e)
5
{
6
if (!IsPostBack)
7
{
8
if (!Request.Browser.SupportsCallback) throw new ApplicationException("This browser doesn't support Client callbacks.");
9
string src = Page.ClientScript.GetCallbackEventReference(this, "", "ClientCallback", "","ClientErrorCallback" ,true);
10
string mainSrc = @"function DeleteFile(){"+src+"}";
11
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DeleteFile", mainSrc, true);
12
}
13
}
14
15
ICallbackEventHandler Members#region ICallbackEventHandler Members
16
17
public string GetCallbackResult()
18
{
19
return this._returnvalue;
20
}
21
22
public void RaiseCallbackEvent(string eventArgument)
23
{
24
if (Session["unsave"] != null)
25
{
26
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
27
AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
28
string sPath = Server.MapPath(appSection.Settings["UploadFilePath"].Value.ToString());
29
string[] files = Session["upload"].ToString().Split(',');
30
foreach (string x in files)
{
31
if (File.Exists(sPath + x)) File.Delete(sPath + x);
32
}
33
Session.Remove("upload");
34
Session.Remove("unsave");
35
this._returnvalue = "deleted";
36
}
37
}
38
39
#endregion
40
}
转载于:https://www.cnblogs.com/LreonWrorld/archive/2007/02/16/651687.html