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

springMVC实现前台带进度条文件上传的示例代码

程序员文章站 2024-03-08 22:15:10
项目框架采用spring+hibernate+springmvc如果上传文件不想使用flash那么你可以采用html5;截图前段模块是bootstarp框架;不废话直接来代...

项目框架采用spring+hibernate+springmvc如果上传文件不想使用flash那么你可以采用html5;截图前段模块是bootstarp框架;不废话直接来代码;spring-mvc配置文件;效果截图如下:

springMVC实现前台带进度条文件上传的示例代码

详细实现如下:

1、mvc-config.xml

<?xml version="1.0" encoding="utf-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"      
    xmlns:context="http://www.springframework.org/schema/context" 
  xmlns:mvc="http://www.springframework.org/schema/mvc" 
  xsi:schemalocation="http://www.springframework.org/schema/beans  
  http://www.springframework.org/schema/beans/spring-beans.xsd 
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.2.xsd 
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> 
 
  <!-- 注解扫描包 --> 
  <context:component-scan base-package="com.yunfang.banks.controllers" /> 
 
  <!-- 开启注解 --> 
  <mvc:annotation-driven /> 
  <!-- 不拦截静态资源 --> 
  <mvc:default-servlet-handler /> 
  <mvc:interceptors> 
    <mvc:interceptor> 
      <mvc:mapping path="/js/" /> 
      <mvc:mapping path="/js/**" /> 
      <bean class="com.yunfang.banks.intreceptor.myinterceptor"></bean> 
    </mvc:interceptor> 
  </mvc:interceptors> 
  <mvc:interceptors> 
    <bean class="com.yunfang.banks.intreceptor.myinterceptor"></bean> 
  </mvc:interceptors> 
  <!-- 静态资源(js/image)的访问 --> 
  <mvc:resources location="/js/" mapping="/js/**" /> 
 
  <!-- 定义视图解析器 --> 
  <bean id="viewresolver" 
    class="org.springframework.web.servlet.view.internalresourceviewresolver"> 
    <property name="prefix" value="/"></property> 
    <property name="suffix" value=""></property> 
  </bean> 
 
  <bean class="org.springframework.web.servlet.mvc.annotation.annotationmethodhandleradapter"> 
    <property name="messageconverters"> 
      <list> 
        <!--下载的时候专用 --> 
        <bean 
          class="org.springframework.http.converter.bytearrayhttpmessageconverter" /> 
        <bean id="jsonhttpmessageconverter" 
          class="org.springframework.http.converter.json.mappingjacksonhttpmessageconverter"> 
          <property name="supportedmediatypes"> 
            <list> 
              <value>text/plain;charset=utf-8</value> 
            </list> 
          </property> 
        </bean> 
      </list> 
    </property> 
  </bean> 
  <!-- 配置springmvc处理上传文件的信息,自定义上传,带进度条 --> 
  <bean id="multipartresolver" class="com.yunfang.banks.listener.custommultipartresolver"> 
      <property name="defaultencoding" value="utf-8" /> 
    <property name="maxuploadsize" value="10000000000" /> 
  </bean> 
    <!--    
    <bean id="multipartresolver" 
    class="org.springframework.web.multipart.commons.commonsmultipartresolver"> 
    <property name="defaultencoding" value="utf-8" /> 
    <property name="maxuploadsize" value="10485760000" /> 
    <property name="maxinmemorysize" value="40960" /> 
  </bean>  
    --> 
   
</beans> 

2、实体工具类:progress.java

package com.yunfang.banks.listener; 
 
public class progress { 
   
  private long pbytesread; 
  private long pcontentlength; 
  private long pitems; 
  public long getpbytesread() { 
    return pbytesread; 
  } 
  public void setpbytesread(long pbytesread) { 
    this.pbytesread = pbytesread; 
  } 
  public long getpcontentlength() { 
    return pcontentlength; 
  } 
  public void setpcontentlength(long pcontentlength) { 
    this.pcontentlength = pcontentlength; 
  } 
  public long getpitems() { 
    return pitems; 
  } 
  public void setpitems(long pitems) { 
    this.pitems = pitems; 
  } 
  @override 
  public string tostring() { 
    return "progress [pbytesread=" + pbytesread + ", pcontentlength=" 
        + pcontentlength + ", pitems=" + pitems + "]"; 
  } 
   
   
   
} 

3、文件上传进度监听类:fileuploadprogresslistener.java

package com.yunfang.banks.listener; 
 
import javax.servlet.http.httpsession; 
import org.apache.commons.fileupload.progresslistener; 
import org.springframework.stereotype.component; 
 
@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); 
  } 
  public void update(long pbytesread, long pcontentlength, int pitems) { 
    progress status = (progress) session.getattribute("status"); 
    try { 
      thread.sleep(5); 
    } catch (interruptedexception e) { 
      e.printstacktrace(); 
    } 
    status.setpbytesread(pbytesread); 
    status.setpcontentlength(pcontentlength); 
    status.setpitems(pitems); 
    //system.out.println(">>>>>>>>>>>>>>>>>>>>"+status); 
     
  } 
 
} 

4、自定义扩展org.springframework.web.multipart.commons.commonsmultipartresolver类,重写public multipartparsingresult parserequest(httpservletrequest request) throws multipartexception方法:

custommultipartresolver.java

package com.yunfang.banks.listener; 
 
import java.util.list; 
 
import javax.servlet.http.httpservletrequest; 
import org.apache.commons.fileupload.servlet.servletfileupload; 
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.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; 
  } 
   
  @override 
  @suppresswarnings("unchecked") 
  public multipartparsingresult parserequest(httpservletrequest request) 
      throws multipartexception { 
    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 ex) { 
      throw new multipartexception("could not parse multipart servlet request", ex); 
    } 
  } 
   
} 

5、uploadcontroller.java

@requestmapping("usercontrollers/progress") 
public void uploadfile(httpservletrequest request,httpservletresponse response, 
            @requestparam("file") commonsmultipartfile file) throws ioexception { 
   response.setcontenttype("text/html"); 
   response.setcharacterencoding("gbk"); 
   printwriter out; 
   boolean flag = false; 
   if (file.getsize() > 0) { 
     //文件上传的位置可以自定义 
     flag = fileuploadutil.uploadfile(file, request); 
   } 
   out = response.getwriter(); 
   if (flag == true) { 
    out.print("1"); 
   } else { 
    out.print("2"); 
   } 
} 

6、fileuploadutil.java

import java.io.file; 
 
import javax.servlet.http.httpservletrequest; 
 
import org.springframework.web.multipart.multipartfile; 
 
public class fileuploadutil { 
   
  public static boolean uploadfile(httpservletrequest request, multipartfile file) { 
     system.out.println("开始"); 
     string path = request.getsession().getservletcontext().getrealpath("upload"); 
     string filename = file.getoriginalfilename(); 
     system.out.println(path); 
     file targetfile = new file(path, filename); 
     if (!targetfile.exists()) { 
       targetfile.mkdirs(); 
     } 
     // 保存 
     try { 
       file.transferto(targetfile); 
       return true; 
     } catch (exception e) { 
       e.printstacktrace(); 
       return false; 
     } 
 
  } 
 
} 

7、前台页面

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> 
<% 
  string path = request.getcontextpath(); 
  string basepath = request.getscheme() + "://" 
      + request.getservername() + ":" + request.getserverport() 
      + path + "/"; 
%> 
 
<!doctype html> 
<html> 
<head> 
<base href="<%=basepath%>"> 
 
 
<meta http-equiv="pragma" content="no-cache"> 
<meta http-equiv="cache-control" content="no-cache"> 
<meta http-equiv="expires" content="0"> 
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="this is my page"> 
<!-- 
 <link rel="stylesheet" type="text/css" href="styles.css"> 
--> 
<link href="css/bootstrap.min.css" rel="stylesheet"> 
 
<style type="text/css"> 
.file-box { 
  position: relative; 
  width: 340px 
} 
 
.txt { 
  height: 22px; 
  border: 1px solid #cdcdcd; 
  width: 180px; 
  vertical-align: middle; 
  margin: 0; 
  padding: 0 
} 
 
.btn { 
  border: 1px solid #cdcdcd; 
  height: 24px; 
  width: 70px; 
  vertical-align: middle; 
  margin: 0; 
  padding: 0 
} 
 
.file { 
  position: absolute; 
  top: 0; 
  right: 80px; 
  height: 24px; 
  filter: alpha(opacity :  0); 
  opacity: 0; 
  width: 260px; 
  vertical-align: middle; 
  margin: 0; 
  padding: 0 
} 
</style> 
<%--<script type="text/javascript"> 
    function myinterval() 
    { 
      $("#progress").html(""); 
      $.ajax({ 
        type: "post", 
        url: "<%=basepath%>usercontrollers/getsessions", 
      data : "1=1", 
      datatype : "text", 
      success : function(msg) { 
        var data = msg; 
        console.log(data); 
        $("#pdiv").css("width", data + "%"); 
        $("#progress").html(data + "%"); 
      } 
    }); 
  } 
  function auttime() { 
    setinterval("myinterval()", 200);//1000为1秒钟 
  } 
</script> 
 
 
--%> 
<script type="text/javascript"> 
  function upladfile() { 
    var fileobj = document.getelementbyid("file").files[0]; // js 获取文件对象 
    var filecontroller = "usercontrollers/progress"; // 接收上传文件的后台地址  
    // 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() { 
      alert("上传完成!"); 
      //$('#mymodal').modal('hide'); 
    }; 
        //监听progress事件 
    xhr.upload.addeventlistener("progress", progressfunction, false); 
    xhr.send(form); 
  } 
  function progressfunction(evt) { 
 
    var progressbar = document.getelementbyid("progressbar"); 
 
    var percentagediv = document.getelementbyid("percentage"); 
 
    if (evt.lengthcomputable) { 
 
      progressbar.max = evt.total; 
 
      progressbar.value = evt.loaded; 
 
      percentagediv.innerhtml = math.round(evt.loaded / evt.total * 100) 
          + "%"; 
 
    } 
 
  } 
</script> 
 
</head> 
 
<body style="width: 80%;height: 80%;margin: 0px auto;"> 
  <div class="row bootstrap-admin-no-edges-padding"> 
    <div class="col-md-12"> 
      <div class="panel panel-default"> 
        <div class="panel-heading"> 
          <div class="text-muted bootstrap-admin-box-title">文件管理</div> 
        </div> 
        <div class="bootstrap-admin-panel-content"> 
          <button class="btn btn-primary btn-lg" data-toggle="modal" 
            data-target="#mymodal">上传</button> 
          <input type="text" id="test"> 
        </div> 
      </div> 
    </div> 
  </div> 
 
  <!-- 模态框(modal) --> 
  <div class="modal fade" id="mymodal" tabindex="-1" role="dialog" 
    aria-labelledby="mymodallabel" aria-hidden="true"> 
    <div class="modal-dialog"> 
      <div class="modal-content"> 
        <div class="modal-header"> 
          <button type="button" class="close" data-dismiss="modal" 
            aria-hidden="true">×</button> 
          <h4 class="modal-title" id="mymodallabel">文件上传进度</h4> 
        </div> 
        <div class="modal-body"> 
          <progress id="progressbar" value="0" max="100" 
            style="width: 100%;height: 20px; "> </progress> 
          <span id="percentage" style="color:blue;"></span> <br> 
          <br> 
          <div class="file-box"> 
            <input type='text' name='textfield' id='textfield' class='txt' /> 
            <input type='button' class='btn' value='浏览...' /> <input 
              type="file" name="file" class="file" id="file" size="28" 
              onchange="document.getelementbyid('textfield').value=this.value" /> 
            <input type="submit" name="submit" class="btn" value="上传" 
              onclick="upladfile()" /> 
             
          </div> 
        </div> 
        <div class="modal-footer"> 
          <button type="button" class="btn btn-default" data-dismiss="modal">关闭 
          </button> 
        </div> 
      </div> 
      <!-- /.modal-content --> 
    </div> 
    <!-- /.modal --> 
  </div> 
  <script type="text/javascript" 
    src="http://code.jquery.com/jquery-2.0.3.min.js"></script> 
  <script src="js/bootstrap.min.js"></script> 
</body> 
</html> 

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