利用 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. 表单提交完成必须清空表单
 

转载于:https://www.cnblogs.com/jiangqiang/p/4091251.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值