首先,我先實現一個傳統的網絡文件上傳方案,建立一個web頁面,我還需要一個<form>和兩個<input>元素就能解決問題,如在Index.aspx文件中有如下元素:
<form id="filePost" action="/Shared/Upload" method="post" enctype="multipart/form-data">
<label> Filename: <input type="file" name="file" /></label>
<input id="ButtonUpload" type="submit" value="Upload" />
</form>
Index.aspx中的內容就寫好了。我看到action="/Shared/Upload"裏面需要一個“Upload”方法響應Post請求,可見,我單擊【Upload】按鈕就能將Post請求到“Upload”這個action裏執行後臺代碼。
後臺代碼:
public ActionResult Upload(HttpPostedFileBase file)
{
if (file.ContentLength == 0) {
return Redirect("/Shared/Error");
}
var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));
try{
file.SaveAs(fileName);
return Redirect("/Home/Index");
}catch{
return Redirect("/Shared/Error");
}
}
這樣,一個傳統的文件上傳方案解決。單擊【Upload】按鈕頁面將會跳轉到“http://...../Shared/Upload”。
2. 實現網絡文件Ajax上傳解決方案
現在對Index.aspx做一部分改動,讓文件上傳方案實現“Ajax”,不需要刷新頁面,也能實現文件上傳,而且可以很好的處理請求返回,這是我們下一步的目標。
1.在Index.aspx頁面添加一個元素,用於顯示請求返回結果。
如:<div id="outputdiv"> </div>
2.在http://jquery.malsup.com/form/#download網站下載jquery.form.js文件,我們調用$.ajaxForm()或者$.ajaxSubmit()函數,實現目標。
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#outputdiv',
beforeSubmit: showRequest,
success: showResponse
};
$('#filePost').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
function showRequest(formData, jqForm, options) {
alert('發送前');
return true;
}
function showResponse(responseText, statusText) {
alert('發送後');
}
</script>
在Index.aspx頁面中添加如上代碼。
3.在<div id="outputdiv"> </div>元素中我希望它能顯示文件上傳的結果,所以,Upload方法返回文本就可以,下面修改Upload方法如下:
public ActionResult Upload(HttpPostedFileBase file)
{
if (file.ContentLength == 0) {
return Content("沒有文件", "text/plain");
}
var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));
try{
file.SaveAs(fileName);
return Content("上傳成功", "text/plain");
}catch{
return Content("上傳失敗", "text/plain");
}
}
實現Ajax文件上傳解決方案。關於jquery.form的更多信息,讀者可看考http://jquery.malsup.com/form/