欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring MVC + bootstrap实现文件上传示例(带进度条)

程序员文章站 2024-03-04 23:20:06
最近学习了bootstrap,有结合了spring mvc写了个文件上传的示例,留做笔记,废话不多说,直接上代码 监听器类fileuploadprogresslist...

最近学习了bootstrap,有结合了spring mvc写了个文件上传的示例,留做笔记,废话不多说,直接上代码

监听器类fileuploadprogresslistener.java

package com.gpl.web.listener;  
import javax.servlet.http.httpsession; 
 
import org.apache.commons.fileupload.progresslistener; 
import org.springframework.stereotype.component; 
 
import com.gpl.web.utils.progress; 
 
 
@component 
public class fileuploadprogresslistener implements progresslistener{ 
 
  private httpsession session; 
   
  public void setsession(httpsession session){ 
    this.session = session; 
    progress status = new progress(); 
    session.setattribute("status", status); 
  } 
  @override 
  public void update(long bytesread, long contentlength, int items) { 
    progress status = (progress) session.getattribute("status"); 
    status.setbytesread(bytesread); 
    status.setcontentlength(contentlength); 
    status.setitems(items); 
  } 
 
} 

customermyltipartresolver.java

package com.gpl.web.listener;  
import java.util.list; 
import javax.servlet.http.httpservletrequest;  
import org.apache.commons.fileupload.fileitem; 
import org.apache.commons.fileupload.fileupload; 
import org.apache.commons.fileupload.fileuploadbase; 
import org.apache.commons.fileupload.fileuploadexception; 
import org.apache.commons.fileupload.servlet.servletfileupload; 
import org.springframework.beans.factory.annotation.autowired; 
import org.springframework.web.multipart.maxuploadsizeexceededexception; 
import org.springframework.web.multipart.multipartexception; 
import org.springframework.web.multipart.commons.commonsmultipartresolver; 
 
public class custommultipartresolver extends commonsmultipartresolver{ 
   
  @autowired 
  private fileuploadprogresslistener progresslistener; 
   
  public void setfileuploadprogresslistener(fileuploadprogresslistener progresslistener){ 
    this.progresslistener = progresslistener; 
  } 
   
  public multipartparsingresult parsingresult(httpservletrequest request){ 
    string encoding = determineencoding(request); 
    fileupload fileupload = preparefileupload(encoding); 
    progresslistener.setsession(request.getsession()); 
    fileupload.setprogresslistener(progresslistener); 
    try{ 
      list<fileitem> fileitems = ((servletfileupload) fileupload).parserequest(request); 
      return parsefileitems(fileitems, encoding); 
    }catch(fileuploadbase.sizelimitexceededexception ex){ 
      throw new maxuploadsizeexceededexception(fileupload.getsizemax(), ex); 
    }catch (fileuploadexception e) { 
      throw new multipartexception("异常",e); 
    } 
  } 
 
} 

进度实体类progress.java

package com.gpl.web.utils; 
public class progress { 
   private long bytesread; 
  private long contentlength; 
  private long items; 
  public long getbytesread() { 
    return bytesread; 
  } 
  public void setbytesread(long bytesread) { 
    this.bytesread = bytesread; 
  } 
  public long getcontentlength() { 
    return contentlength; 
  } 
  public void setcontentlength(long contentlength) { 
    this.contentlength = contentlength; 
  } 
  public long getitems() { 
    return items; 
  } 
  public void setitems(long items) { 
    this.items = items; 
  } 
  @override 
  public string tostring() { 
    return "progress [bytesread=" + bytesread + ", contentlength=" + contentlength + ", items=" + items + "]"; 
  } 
   
   
} 

spring配置文件需加入如下bean

<!-- 文件上传 --> 
  <bean id="multipartresolver" class="com.gpl.web.listener.custommultipartresolver"> 
    <property name="defaultencoding" value="utf-8"></property> 
    <property name="maxuploadsize" value="838860800"></property> 
  </bean> 

controller层实现

/** 
   * 文件上传 
   * @param request 
   * @param response 
   * @param file 
   * @throws ioexception 
   */ 
  @requestmapping(value = "/upload", method = requestmethod.post) 
  public void upload(httpservletrequest request,httpservletresponse response,@requestparam("file") commonsmultipartfile file) 
      { 
    try{ 
      printwriter out; 
      boolean flag = false; 
      if(file.getsize() > 0){ 
        string path = "/asserts/upload/files/excel/"; 
        string uploadpath = request.getsession().getservletcontext().getrealpath(path); 
        system.out.println(uploadpath); 
        fileutils.copyinputstreamtofile(file.getinputstream(), new file(uploadpath,file.getoriginalfilename())); 
        flag = true; 
      } 
      out = response.getwriter(); 
      if(flag == true){ 
        out.print("1"); 
      }else{ 
        out.print("2"); 
      } 
    }catch(exception e){ 
      e.printstacktrace(); 
    } 
     
  } 

前端代码

<div id="uploadfiledlg" class="easyui-dialog" style="width:800px;text-align:center;" 
      closed="true"> 
      <form id="uploadfileform" method="post" style="width:100%;text-align:center;padding:20px 0;"> 
        <input id="file" type="file" style="width:500px;display:inline-block;"> 
        <button id="uploadbtn" class="easyui-linkbutton" style="width:auto;display:inline-block;">上传</button>  
      </form> 
      <div class="progress progress-bar-striped active" style="display:none;"> 
        <div id="progressbar" class="progress-bar progress-bar-info" role="progressbar" 
        aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" 
        style="width:0%;"> 
        </div> 
      </div> 
      <table id="uploadbatchdg"></table> 
    </div> 

页面ready加入的js代码

$("#uploadbtn").attr("disabled",false); 
    $("#uploadbtn").click(function(){ 
      var filevalue = $("#file").val(); 
      if(filevalue == null || filevalue == ""){ 
        layer.msg("请先选择文件"); 
        return; 
      } 
      var obj = $("#file"); 
      var photoext=obj.val().substr(obj.val().lastindexof(".")).tolowercase();//获得文件后缀名 
      if(photoext!=".xls" && photoext!=".xlsx"){ 
        layer.msg("请选择xls或是xlsx格式的文件,不支持其他格式文件"); 
        return false; 
      } 
      var filesize = 0; 
      var isie = /msie/i.test(navigator.useragent) && !window.opera;    
      if (isie && !obj.files) {    
        var filepath = obj.val();    
        var filesystem = new activexobject("scripting.filesystemobject");  
        var file = filesystem.getfile (filepath);     
        filesize = file.size;    
      }else {  
        filesize = obj.get(0).files[0].size;   
      }  
      filesize=math.round(filesize/1024*100)/100; //单位为kb 
      if(filesize > 5000){ 
        layer.msg("文件不能大于5m"); 
        return false; 
      } 
      $("#progressbar").width("0%"); 
      $(this).attr("disabled",true); 
      $("#progressbar").parent().show(); 
      $("#progressbar").parent().addclass("active"); 
      uploadfile(); 

上传文件js代码

function uploadfile() { 
      var fileobj = $("#file").get(0).files[0]; // js 获取文件对象 
      console.info("上传的文件:"+fileobj); 
      var filecontroller = "${basepath}/batch/upload"; // 接收上传文件的后台地址  
      // formdata 对象 
      var form = new formdata(); 
      // form.append("author", "hooyes"); // 可以增加表单数据 
      form.append("file", fileobj); // 文件对象 
      // xmlhttprequest 对象 
      var xhr = new xmlhttprequest(); 
      xhr.open("post", filecontroller, true); 
      xhr.onload = function() { 
        layer.msg("上传完成"); 
        $("#uploadbtn").attr('disabled', false); 
        $("#uploadbtn").val("上传"); 
        $("#progressbar").parent().removeclass("active"); 
        $("#progressbar").parent().hide(); 
      }; 
      xhr.upload.addeventlistener("progress", progressfunction, false); 
      xhr.send(form); 
    } 
    
    function progressfunction(evt) { 
      var progressbar = $("#progressbar"); 
      if (evt.lengthcomputable) { 
        var completepercent = math.round(evt.loaded / evt.total * 100)+ "%"; 
        progressbar.width(completepercent); 
        $("#uploadbtn").val("正在上传 " + completepercent); 
      } 
    }; 

效果图

spring MVC + bootstrap实现文件上传示例(带进度条)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。