轉自:http://www.cnblogs.com/sibiyellow/archive/2012/04/27/jqueryformjs.html
最近專案裡面涉及到無重新整理上傳圖片的功能,其實也就是上傳一些封面,然後我就想當選擇圖片的時候,右邊出現預覽圖(在沒有上傳到伺服器的情況下),當點選上傳的時候在上傳到伺服器(無重新整理上傳),所以也就找了些資料,做了下這方面的功能。
折騰著,折騰著,也就折騰出來啦。現在在這寫個筆記。
首先是預覽功能,使用了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="data: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;
}
}

程式碼到這裡一個簡單的例子也就完成啦。附上小例子的原始碼: