spring mvc实现进度上传有两种方式
1. 重写 CustomMultipartResolver 里面的方法,加个监听器。
2.本文记录另一种更简单的办法,利用jquery+html5即可实现读取文件上传进度
spring mvc xml
<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>
controller
@RequestMapping("/upload") public @ResponseBody Object uploadFile(HttpServletRequest request,@RequestParam(value = "file") MultipartFile... files) throws InterruptedException { try { for (MultipartFile f : files) { if (f.getSize() > 0) { File targetFile = new File("F:/a.doc"); f.transferTo(targetFile);//写入目标文件 } } return "ok"; } catch (Exception e) { System.out.println("error!"); } return null; }
jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <title>文件上存</title> <script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> <script> $(function () { $("#upload_file").on('click', function () { var data = new FormData(); data.append('file', $("#file")[0].files[0]); //new FormData($('#uploadForm')[0]) $.ajax({ data: data, url: "upload", type: 'post', contentType: false, processData: false, xhr: function () { //这是关键 获取原生的xhr对象 做以前做的所有事情 var xhr = jQuery.ajaxSettings.xhr(); xhr.upload.onload = function () { alert('finish downloading') } xhr.upload.onprogress = function (evt) { if (evt.lengthComputable) { var progressBar = document.getElementById("progressBar"); var percentageDiv = document.getElementById("percentage"); if (evt.lengthComputable) { var percent = evt.loaded / evt.total * 100; console.log(percent,evt); progressBar.max = evt.total; progressBar.value = evt.loaded; $(percentageDiv).html(Math.round(percent) + "%"); } } } return xhr; }, success: function () { alert("ok"); }, error: function () { } }); }); }); </script> </head> <body> <div class="container"> <progress id="progressBar" value="13" max="100"></progress> <span id="percentage"></span> <input id="file" type="file" name="file"> <input id="upload_file" class="btn btn-primary" type="button" value="上存"> </div> </body> </html>