轉自:http://www.cnblogs.com/sibiyellow/archive/2012/04/27/jqueryformjs.htmlhtml
最近項目裏面涉及到無刷新上傳圖片的功能,其實也就是上傳一些封面,而後我就想當選擇圖片的時候,右邊出現預覽圖(在沒有上傳到服務器的狀況下),當點擊上傳的時候在上傳到服務器(無刷新上傳),因此也就找了些資料,作了下這方面的功能。jquery
折騰着,折騰着,也就折騰出來啦。如今在這寫個筆記。ajax
首先是預覽功能,使用了cloudgamer的JavaScript 圖片上傳預覽效果,這裏也遇到了些問題,就是我會在File控件的後面設置一個按鈕來清空前面File裏面的值,而且在預覽圖片的地方顯示默認的圖片(是爲了項目裏面,當這條記錄有封面時,則顯示他的封面圖片)。瀏覽器
JS代碼以下:服務器
//清空File控件的值,而且預覽處顯示默認的圖片 function clearFileInput() { var form = document.createElement('form'); document.body.appendChild(form); //記住file在舊錶單中的的位置 var file = document.getElementById("idFile"); var pos = file.nextSibling; form.appendChild(file); form.reset();//經過reset來清空File控件的值 document.getElementById("colspan").appendChild(file); document.body.removeChild(form); //在預覽處顯示圖片 這是在瀏覽器支持濾鏡的狀況使用的 document.getElementById("idImg").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='images/abshiu.jpg'"; //這是是火狐裏面顯示默認圖片的 if (navigator.userAgent.indexOf('Firefox') >= 0) { $("#idImg").attr('src', 'images/abshiu.jpg'); } }
HTML代碼以下:app
<table border="0" class="perview"> <tr> <th width="45%">選擇文件</th> <th width="45%">預覽圖</th> <th width="10%">上傳圖片</th> </tr> <tr> <td><span id="colspan"><input id="idFile" runat="server" name="pic" type="file" /></span> <input type="button" id="resets" name="resets" value="還原" onclick="clearFileInput()" /> </td> <td align="center"><img id="idImg" src="images/abshiu.jpg" /> </td> <td><input type="button" name="resets" value="上傳保存圖片" onclick="upLoadFile()" /> </td> </tr> </table> <script> var ip = new ImagePreview($$("idFile"), $$("idImg"), { maxWidth: 200, maxHeight: 200, action: "ImagePreview.ashx" }); ip.img.src = ImagePreview.TRANSPARENT; ip.file.onchange = function() { ip.preview(); }; </script>
作到這裏的話 預覽效果就已經搞定啦,而後就是無刷新上傳,雖然cloudgamer的博客裏面有簡便無刷新文件上傳系統,可是我沒有采用,而是使用了jquery.form.js來作無刷新上傳效果,代碼以下:dom
function upLoadFile() { var options = { type: "POST", url: 'Files.ashx', success: showResponse }; // 將options傳給ajaxForm $('#myForm').ajaxSubmit(options); } function showResponse() { alert("上傳成功!"); }
關於jquery.form.js的API,百度下吧。#myForm就是頁面的form的ID,Files.ashx則負責圖片的上傳處理,Files.ashx的代碼以下:post
public class File_WebHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpFileCollection files = context.Request.Files; if (files.Count > 0) { Random rnd = new Random(); for (int i = 0; i < files.Count; i++) { HttpPostedFile file = files[i]; if (file.ContentLength > 0) { string fileName = file.FileName; string extension = Path.GetExtension(fileName); int num = rnd.Next(5000, 10000); string path = "file/" + num.ToString() + extension; file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path)); } } } } public bool IsReusable { get { return false; } }
代碼到這裏一個簡單的例子也就完成啦。附上小例子的源碼:ui
圖片上傳預覽及無刷新上傳url