當咱們作後臺管理頁面一般須要作一個文件上傳,可是若是多個頁面上傳的時候咱們會去作一個一個的上傳代碼嗎?若是你仍是,那麼 oh shit !javascript
個人思路是作一個上傳文件功能的頁面,而後用iframe將當前上傳頁面嵌套進來,而後在上傳頁面作一個上傳成功時候將上傳的url用javascript通知window.openner對象頁面的值。html
html頁面以下Yeml_File_Uploadjava
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>無標題文檔</title> </head> <body><iframe src="Yeml_File_Upload.aspx" width="100%" height="30" frameborder="0"> </iframe> </body> </html>
.aspx函數
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>文件上傳</title> </head> <body> <form id="form1" runat="server"> <!-- author:葉明龍 createTime:2013-08-08 descript:上傳成功,將圖片所在的根目錄的返回在本頁面的隱藏域中,便於window.opener訪問本頁面的上傳路徑。 客戶端生成了upladSucess(upoad_url)函數,可直接在parent頁面直接調用本頁面的upoad_url。 --> <asp:FileUpload ID="file_upload" runat="server" /> <asp:Button ID="btn_upload" runat="server" Text="上傳" OnClick="btn_upload_Click" /> <input type="hidden" id="hidd_upoad_url" runat="server" /> </form> </body> </html>
protected void btn_upload_Click(object sender, EventArgs e) { // String path = Server.MapPath("~/UploadedImages/"); if (file_upload.HasFile) { bool fileOK = false; String fileExtension = Path.GetExtension(file_upload.FileName).ToLower(); String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" }; for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileOK = true; } } if (!fileOK) { return; } string path = string.Format("/UploadImages/jhrz_images/{0}/", DateTime.Now.ToString("yyyyMMdd")); if (!Directory.Exists(Server.MapPath("~" + path))) Directory.CreateDirectory(Server.MapPath("~" + path)); string file_name = string.Format("{0}{1}{2}", path, Guid.NewGuid(), fileExtension); file_upload.SaveAs(Server.MapPath(file_name)); hidd_upoad_url.Value = file_name; ClientScript.RegisterStartupScript(GetType(), "upload_success", "<script type='text/javascript'>parent.upladSucess('" + file_name + "');</script>", false); } }
例如是1.html ui
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>無標題文檔</title> <script type="text/javascript"> /** *圖片上傳成功callback */ function upladSucess(img_url) { // alert(img_url); document.getElementById("img1").setAttribute("src",img_url); } </script> </head> <body> <img id="img1" src="" /> <iframe src="Yeml_File_Upload.aspx" width="100%" height="30" frameborder="0"> </iframe> </body> </html>
剩下若是還有2.html,3.html,**.aspx須要上傳文件的時候咱們只須要在每一個頁面重寫url
/** *圖片上傳成功callback */ function upladSucess(img_url) { // alert(img_url); document.getElementById("img1").setAttribute("src",img_url); }
來邏輯咱們的頁面賦值操做就行了!spa