利用 JQuery Input file 实现单文件上传

引用 jquery.form.js 文件
利用JQuery Input file  实现单文件上传
效果如下

初始按钮
  
点击按钮 弹出 选中框
  

 页面代码:

<a class="btn" style="background-image: url(img/btnbg_minidept.png);">
<input type="file" id="fileMiniDept" class="file" name="uploadFile" /></a>
.file
{
    filter:alpha(opacity=0);
    -moz-opacity:0;
    opacity: 0;
    width: 250px;
    height: 30px;
    font-size: 18px;
    cursor:pointer;
    float:right;
    overflow:hidden;
}
让 file 透明 显示 a 标签的 背景图

jQuery代码

引用jquery.form.js 插件 可以用 ajaxSubmit 随时提交表单

$(function() {
    //file控件 值改变时触发提交事件
    $("#fileMiniDept").change(
   function() {
       $("#aspnetForm").ajaxSubmit({
           url: 'Ajax_ashx/LSP_M_ExcelImport_MiniDepart.ashx?fileId=' + $(this).attr("id"),
           beforeSubmit: function() {
              //提交前 验证
           },
           success: function(data) {
               //成功操作
               //表单清空
               $('#aspnetForm')[0].reset()
           },
           error: function() {
                //失败操作
               $('#aspnetForm')[0].reset()
           }
       });

   });
});

后台文件
新建 LSP_M_ExcelImport_MiniDepart.ashx 处理文件

  public class UploadFile : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string strReturn = "";
            try
            {
                context.Response.ContentType = "text/plain";
                //判断提交文件数量
                if (context.Request.Files.Count > 0)
                {
                    //获取提交文件
                    HttpPostedFile file = context.Request.Files[0];
                    //保存文件
                    string path = context.Server.MapPath("~/uploadFile/");
                    string filePath = path + "/" + Guid.NewGuid().ToString() + type;
                    file.SaveAs(filePath);
}
else { strReturn = "SaveError"; } } catch { strReturn = "SaveError"; } //返回保存状态 context.Response.Write(strReturn); } };

 注意点 

1. input file 必须有name 属性 ,css 必须设置为透明

2. 表单提交完成必须清空表单
 

posted @ 2014-11-12 10:04  巴顿道儿  阅读(2923)  评论(0编辑  收藏  举报