javascript文件上传.doc,.pdf,.docx等格式

               1、 由于input的type="file"的默认属性比较丑,所以我们要隐藏input标签,这里用的是定位。

               2、通过class="enclosure-text"这个P标签来存放我们所上传后的文件名

               3、由于input是隐藏的,所以我们要加一个上传按钮,并添加点击事件去触发input的点击事件

HTML:

<div class="comment-right-float">
        <p class="enclosure-text"></p>
         <span class="btn-up-file" onclick="$('#file-input').click()">上传</span>
          <form action="/ueditor/upload" method="post" id="submitFile">   <!-action为后台给的接口路径->
                   <input type="file" id="file-input" name="file-att" style="visibility: hidden;display: inline-block;width:                                                       2px;position: fixed;left: -1000px;" accept=".doc,.pdf,.docx" />    
           </form>
           <span class="file-tip">支持doc/docx/pdf等格式</span>
           <p class="warning-manage enclosure-null hide ">附件不能为空</p>
 </div>    

JS:

//    选择附件上传 
   var fileUrl;  //需要的url,在保存时后台需要这个地址
   var saveFileName;  //上传完成后截取的文件名
   $('#file-input').change(function(){ 
     //判断文件名是否为空,不为空时截取文件的名
     if($(this).val() == ''){ 
       return false; 
     }else{
         saveFileName=$(this).val().slice(12);
         $(".enclosure-text").text(saveFileName);
     }
     $('#submitFile').ajaxSubmit({ 
       type:'post', 
       dataType:'json', 
       success:function(result){ 
         //请求成功后后台会返回一个URL 地址,该地址是你最后保存时需要提交给后台的。
              fileUrl=result.url;
         //并且清空原文件,不然选择相同文件不能再次传 
//       $('#file-input').val(''); 
       }, 
       error:function(){ 
         //并且清空原文件,不然选择相同文件不能再次传 
//       $('#file-input').val(''); 
       } 
     }); 
})

猜你喜欢

转载自blog.csdn.net/weixin_41760500/article/details/86487476