运用onbeforeunload和GetCallBackEventReference删除未提交的上传文件

在做论坛的时候经常会遇到客户上传文件后,没有提交,那么文件就会遗留在服务器上,当然有另外的解决办法,今天我给出一种方法来使得用户离开页面之后如果未提交的话会自动删除上传文件.原理很简单,就是当用户离开的时候触发onbeforeunload事件,然后利用客户端回调删除服务端数据.
我把上传页面放在单独的一个iframe里面PostMessage.aspx:
ContractedBlock.gif ExpandedBlockStart.gif
 1None.gifpublic partial class PostMessage : System.Web.UI.Page
 2ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 3InBlock.gif    protected void Page_Load(object sender, EventArgs e)
 4ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 5InBlock.gif        this.lbuploaderror.Text = "";
 6InBlock.gif     
 7ExpandedSubBlockEnd.gif    }

 8InBlock.gif    protected void btnUpload_Click(object sender, EventArgs e)
 9ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
10InBlock.gif        string htmlpath="http://" +Context.Request.Url.Host + Context.Request.ApplicationPath ;
11InBlock.gif        if (this.FileUpload1.PostedFile.FileName.ToString() == "")
12ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
13InBlock.gif            this.lbuploaderror.Text = "Please select a file to upload!";
14InBlock.gif            return;
15ExpandedSubBlockEnd.gif        }

16InBlock.gif        try
17ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
18InBlock.gif            if (this.FileUpload1.PostedFile.FileName.ToString() != "")
19ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
20InBlock.gif                Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
21InBlock.gif                AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
22InBlock.gif                string sPath =Server.MapPath(appSection.Settings["UploadFilePath"].Value.ToString());
23InBlock.gif               
24InBlock.gif               
25InBlock.gif               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);
26InBlock.gif               
27InBlock.gif                if (this.FileUpload1.PostedFile != null && this.FileUpload1.PostedFile.FileName.Substring(this.FileUpload1.PostedFile.FileName.IndexOf("."+ 1!= "")
28ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
29InBlock.gif                    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)
30ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
31InBlock.gif                        Page.RegisterStartupScript("""<script language='JavaScript'>alert('Only these file(*.png;*.gif;*.jpg;*.bmp;*.jpeg,*.rar,*.zip) allowed!');</script>");
32InBlock.gif                        return;
33ExpandedSubBlockStart.gifContractedSubBlock.gif                    }
/**////End of if
34InBlock.gif                    if (this.FileUpload1.PostedFile.ContentLength > 200000)
35ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
36InBlock.gif                      
37InBlock.gif                        Page.RegisterStartupScript("""<script language='JavaScript'>alert('Picture file should no more than 200k!');</script>");
38InBlock.gif                        return;
39ExpandedSubBlockStart.gifContractedSubBlock.gif                    }
/**////End of if
40InBlock.gif                   // string sPath = uploadFolder;
41InBlock.gif                    try
42ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
43InBlock.gif                        this.FileUpload1.PostedFile.SaveAs(sPath + savename);
44InBlock.gif                        if (savename.ToLower().IndexOf("rar"> 0 || savename.ToLower().IndexOf("zip"> 0)
45ExpandedSubBlockStart.gifContractedSubBlock.gif                        dot.gif{
46InBlock.gif                            this.FreeTextBox1.Text += "<a href='" + htmlpath + "/" + appSection.Settings["UploadFilePath"].Value.ToString().Substring(2+ savename + "'>"+savename+"</a>";
47ExpandedSubBlockEnd.gif                        }

48InBlock.gif                        else  this.FreeTextBox1.Text += "<img src='" + htmlpath+"/" + appSection.Settings["UploadFilePath"].Value.ToString().Substring(2+savename+"'/>";
49InBlock.gif                        if (Session["upload"== null) Session["upload"= savename;
50InBlock.gif                        else Session["upload"+= "," + savename;
51InBlock.gif                        Session["unsave"= "yes";
52ExpandedSubBlockEnd.gif                    }

53InBlock.gif                    catch
54ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
55InBlock.gif                        Page.RegisterStartupScript("""<script language='JavaScript'>alert('Upload picture failed');</script>");
56InBlock.gif                        return;
57ExpandedSubBlockEnd.gif                    }

58ExpandedSubBlockStart.gifContractedSubBlock.gif                }
/**////End of if
59ExpandedSubBlockEnd.gif            }

60ExpandedSubBlockEnd.gif        }

61InBlock.gif        catch
62ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
63InBlock.gif        
64InBlock.gif            Page.RegisterStartupScript("""<script language='JavaScript'>alert('Upload picture failed');</script>");
65InBlock.gif            return;
66ExpandedSubBlockEnd.gif        }

67ExpandedSubBlockEnd.gif    }

主页面的页面文件:

ContractedBlock.gif ExpandedBlockStart.gif
 1None.gif<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
 2ExpandedBlockStart.gifContractedBlock.gif<script>dot.gif function deletefile()dot.gif{
 3InBlock.gif DeleteFile();
 4ExpandedSubBlockEnd.gif}

 5ExpandedSubBlockStart.gifContractedSubBlock.giffunction ClientCallback(result,context)dot.gif{
 6InBlock.gifalert(result);
 7ExpandedSubBlockEnd.gif}

 8ExpandedSubBlockStart.gifContractedSubBlock.giffunction ClientErrorCallback(error,context)dot.gif{
 9InBlock.gifalert(error);
10ExpandedSubBlockEnd.gif}

11ExpandedSubBlockStart.gifContractedSubBlock.giffunction document.body.onbeforeunload()dot.gif{
12InBlock.gifdeletefile();
13ExpandedBlockEnd.gif}

14None.gif
</script>
15None.gif<div style=" width:100%"><iframe   width=100% height=100% frameborder =no src="PostMessage.aspx"></iframe></div>
16None.gif</asp:Content>
17None.gif
后台代码:
ContractedBlock.gif ExpandedBlockStart.gif
 1None.gifpublic partial class Forum_Detail : System.Web.UI.Page,ICallbackEventHandler 
 2ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 3InBlock.gif    string _returnvalue="";
 4InBlock.gif    protected void Page_Load(object sender, EventArgs e)
 5ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 6InBlock.gif        if (!IsPostBack)
 7ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 8InBlock.gif            if (!Request.Browser.SupportsCallback) throw new ApplicationException("This browser doesn't support Client callbacks.");
 9InBlock.gif            string src = Page.ClientScript.GetCallbackEventReference(this"""ClientCallback""","ClientErrorCallback" ,true);
10InBlock.gif            string mainSrc = @"function DeleteFile(){"+src+"}";
11InBlock.gif            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DeleteFile", mainSrc, true);
12ExpandedSubBlockEnd.gif        }

13ExpandedSubBlockEnd.gif    }

14InBlock.gif
15ContractedSubBlock.gifExpandedSubBlockStart.gif    ICallbackEventHandler Members#region ICallbackEventHandler Members
16InBlock.gif
17InBlock.gif    public string GetCallbackResult()
18ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
19InBlock.gif        return this._returnvalue;
20ExpandedSubBlockEnd.gif    }

21InBlock.gif
22InBlock.gif    public void RaiseCallbackEvent(string eventArgument)
23ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
24InBlock.gif        if (Session["unsave"!= null)
25ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
26InBlock.gif            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
27InBlock.gif            AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
28InBlock.gif            string sPath = Server.MapPath(appSection.Settings["UploadFilePath"].Value.ToString());
29InBlock.gif            string[] files = Session["upload"].ToString().Split(',');
30ExpandedSubBlockStart.gifContractedSubBlock.gif            foreach (string x in files)dot.gif{
31InBlock.gif                if (File.Exists(sPath + x)) File.Delete(sPath + x);
32ExpandedSubBlockEnd.gif            }

33InBlock.gif            Session.Remove("upload");
34InBlock.gif            Session.Remove("unsave");
35InBlock.gif            this._returnvalue = "deleted";
36ExpandedSubBlockEnd.gif        }

37ExpandedSubBlockEnd.gif    }

38InBlock.gif
39ExpandedSubBlockEnd.gif    #endregion

40ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/LreonWrorld/archive/2007/02/16/651687.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值