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 

posted on 2012-04-27 09:34  吴勇寿  阅读(10122)  评论(1编辑  收藏  举报