最近項目里面涉及到無刷新上傳圖片的功能,其實也就是上傳一些封面,然后我就想當選擇圖片的時候,右邊出現預覽圖(在沒有上傳到服務器的情況下),當點擊上傳的時候在上傳到服務器(無刷新上傳),所以也就找了些資料,做了下這方面的功能。
折騰着,折騰着,也就折騰出來啦。現在在這寫個筆記。
首先是預覽功能,使用了 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代碼如下:
<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來做無刷新上傳效果,代碼如下:
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的代碼如下:
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; } }
代碼到這里一個簡單的例子也就完成啦。附上小例子的源碼: