1. View頁面代碼
View Code 1 <script src="http://www.cnblogs.com/Scripts/jquery.form.js" type="text/javascript"></script>
2
3 <form id="filePost" action="/Home/Upload" method="post" enctype="multipart/form-data">
4
5 <label> Filename: <input type="file" name="file" onchange="save();"/></label>
6 <input id="ButtonUpload" type="submit" value="Upload" />
7 </form>
8
9 <div id="outputdiv"> </div
2.Controller頁面
View Code 1 public JsonResult Upload(HttpPostedFileBase file)
2 {
3
4 if (file.ContentLength == 0)
5 {
6 return Json(new
7 {
8 bRet = false,
9 sMsg = "請選擇圖片!"
10 }, "text/html");
11 }
12 //上傳檔案代碼 記得先建立一下 Upload 檔案夾
13 var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));
14 try
15 {
16 file.SaveAs(fileName);
17
18 return Json(new
19 {
20 bRet = true,
21 sMsg = "上傳成功"
22 }, "text/html");
23 }
24 catch
25 {
26 return Json(new
27 {
28 bRet = false,
29 sMsg = "上傳失敗"
30 }, "text/html");
31 }
32
3.javascript
View Code 1 function save() {
2 var options = {
3
4 beforeSubmit: showRequest,
5 error: showError,
6 success: showResponse
7 };
8
9 $('#filePost').ajaxSubmit(options);
10 }
11
12 $(document).ready(function () {
13 var options = {
14 target: '#outputdiv',
15 beforeSubmit: showRequest,
16 error: showError,
17 success: showResponse
18 };
19 $('#filePost').submit(function () {
20 $(this).ajaxSubmit(options);
21 return false;
22 });
23 });
24 function showRequest(formData, jqForm, options) {
25 alert('發送前');
26 return true;
27 }
28 function showError(data) {
29 alert('error');
30 }
31
32 function showResponse(responseText, statusText) {
33
34 alert(responseText + "," + statusText + "," + '發送後');
35
4 jquery.form.js 下載
/Files/YSO1983/jquery.form.rar