jQuery.form 上传文件

今年大部分是都在完善产品,这几天遇到了一个问题,原来的flash组件不支持苹果浏览器,需要改。在网上搜了下,看到一个jQuery.form插件可以上传文件,并且兼容性很好,主要浏览器大部分都兼容,插件官网: http://malsup.com/jquery/form/。还有就是需要jQuery类库。

结果图片:

 jQuery.form 上传文件

前端代码:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />

    <title>文件上传</title>

    <style type="text/css">

        .btn {

            position: relative;

            background-color: blue;

            width: 80px;

            text-align: center;

            font-size: 12px;

            color: white;

            line-height: 30px;

            height: 30px;

            border-radius: 4px;

        }

            .btn:hover {

                cursor: pointer;

            }

            .btn input {

                opacity: 0;

                filter: alpha(opacity=0);

                position: absolute;

                top: 0px;

                left: 0px;

                line-height: 30px;

                height: 30px;

                width: 80px;

            }

        #fileLsit li span {

            margin-left: 10px;

            color: red;

        }

        #fileLsit {

            font-size: 12px;

            list-style-type: none;

        }

    </style>

</head>

<body>

    <div class="btn">

        <span>添加附件</span>
    <!--这里注意:file 标签必须具有name属性,由于没有加name属性,文件上传不到服务到哪--> <input type="file" id="fileName" name="fileName" /> </div> <ul id="fileLsit"> </ul> <!--引入jquery类库--> <script type="text/javascript" src="jquery/jquery.min.js"></script> <!--引入jquery.form插件--> <script type="text/javascript" src="jQuery-Form/jquery.form.js"></script> <script type="text/javascript"> jQuery(function () { var option = { type: 'post', dataType: 'json', //数据格式为json resetForm: true, beforeSubmit: showRequest,//提交前事件 uploadProgress: uploadProgress,//正在提交的时间 success: showResponse//上传完毕的事件 } jQuery('#fileName').wrap( '<form method="post" action="/uploads/upload.ashx?option=upload" id="myForm2" enctype="multipart/form-data"></form>'); jQuery('#fileName').change(function () { $('#myForm2').ajaxSubmit(option); }); }); //删除文件 var deleteFile = function (path, guid) { jQuery.getJSON('/uploads/upload.ashx?option=delete', { path: path }, function (reslut) { if (reslut[0].success) {//删除成功 jQuery('#' + guid).remove(); } else {//删除失败 alert(reslut[0].info); } }); } //上传中 var uploadProgress = function (event, position, total, percentComplete) { jQuery('.btn span').text('上传中...'); } //开始提交 function showRequest(formData, jqForm, options) { jQuery('.btn span').text('开始上传..'); var queryString = $.param(formData); } //上传完成 var showResponse = function (responseText, statusText, xhr, $form) { if (responseText[0].success) {
         //成功之后返回文件地址、文件名称等信息 拼接呈现到html里面。 var str = '<li id="' + responseText[0].guid + '"><a href="' + responseText[0].path + '">' + responseText[0].fileName + '</a><span onclick="deleteFile(\'' + responseText[0].path + '\',\'' + responseText[0].guid + '\')" >删除</span></li>'; jQuery('#fileLsit').append(str); } jQuery('.btn span').text('上传完成'); jQuery('.btn span').text('添加附件'); } </script> </body> </html>

后台代码:相对简单,没有做严格的处理

 1 using System;

 2 using System.Collections.Generic;

 3 using System.IO;

 4 using System.Linq;

 5 using System.Web;

 6 

 7 namespace Demo.uploads

 8 {

 9     /// <summary>

10     /// upload 的摘要说明

11     /// </summary>

12     public class upload : IHttpHandler

13     {

14         //特别说:在返回自己拼接的json格式数据,必须严格,出了bool、数字类型可以不加引号,其他必须加引号。不然在高版本的jQuery.js类库是不会走 success 事件的。

15         public void ProcessRequest(HttpContext context)

16         {

17             context.Response.ContentType = "text/plain";

18 

19             //标志 操作文件的类型 

20             string option = context.Request["option"];

21             switch (option)

22             { 

23                 case "upload":

24                     UploadFile(context);

25                     break;

26                 case "delete":

27                     DeleteFile(context);

28                     break;

29             }

30 

31 

32 

33         }

34         /// <summary>

35         /// 删除文件的方法

36         /// </summary>

37         /// <param name="context"></param>

38         private void DeleteFile(HttpContext context)

39         {

40             string path = context.Request["path"];

41             try

42             {

43                 File.Delete(context.Server.MapPath(path));

44                 context.Response.Write("[{\"success\":true}]");

45 

46             }

47             catch (Exception e)

48             {

49                 context.Response.Write("[{\"success\":false},\"info\":\"" + e.ToString() + "\"]");

50 

51             }

52             finally 

53             {

54                 context.Response.End();

55             }

56         }

57         /// <summary>

58         /// 上传文件方法

59         /// </summary>

60         /// <param name="context"></param>

61         private void UploadFile(HttpContext context)

62         {

63             try

64             {

65                 HttpPostedFile file = context.Request.Files[0];

66                 string fileName = file.FileName;

67                 string path = "/fileUploads/" + fileName;

68                 file.SaveAs(context.Server.MapPath(path));

69                 //这里在返回信息的时候 给以个guid,因为在删除的时候方便 。

70                 string str = "[{\"success\":true,\"fileName\":\"" + fileName + "\",\"path\":\"" + path + "\",\"guid\":\"" + Guid.NewGuid().ToString() + "\"}]";

71                 context.Response.Write(str);

72                 context.Response.End();

73 

74             }

75             catch (HttpException e)

76             {

77                 context.Response.Write("[{\"success\":false,\"info\":\"" + e.ToString() + "\"}]");

78                 context.Response.End();

79             }

80         }

81         public bool IsReusable

82         {

83             get

84             {

85                 return false;

86             }

87         }

88     }

89 }

 

你可能感兴趣的:(jquery)