SpringMVC上传文件进度显示

效果图:

FileUploadController.java

import java.io.File;
import java.util.List;  

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;  

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;  

@Controller
public class FileUploadController {
    Logger log = Logger.getLogger(FileUploadController.class);  

    @RequestMapping(value = "/touploadfile", method = RequestMethod.GET)
    public ModelAndView toUpload(HttpServletRequest request,
            HttpServletResponse response) throws Exception{
				return new ModelAndView("upload2");

    }
    /**
     * upload  上传文件
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadfile2", method = RequestMethod.POST)
    public ModelAndView upload(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        final HttpSession hs = request.getSession();
        ModelAndView mv = new ModelAndView();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(!isMultipart){
            return mv;
        }
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();  

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setProgressListener(new ProgressListener(){
               public void update(long pBytesRead, long pContentLength, int pItems) {
                   ProcessInfo pri = new ProcessInfo();
                   pri.itemNum = pItems;
                   pri.readSize = pBytesRead;
                   pri.totalSize = pContentLength;
                   pri.show = pBytesRead+"/"+pContentLength+" byte";
                   pri.rate = Math.round(new Float(pBytesRead) / new Float(pContentLength)*100);
                   hs.setAttribute("proInfo", pri);
               }
            });
        List<FileItem> items = upload.parseRequest(request);
        String path = request.getSession().getServletContext().getRealPath("upload");
        System.out.println(path);
        for(FileItem item : items){
			if(item.isFormField()){

			}else{
				System.out.println(path +"/"+  item.getFieldName());
				File targetFile = new File(path +"/"+ item.getName());
				if(!targetFile.exists()){
					targetFile.createNewFile();
				}
				item.write(targetFile);
			}
		}
        System.out.println("上传文件的个数为:" + items.size());
        return mv;
    }  

    /**
     * process 获取进度
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/process", method = RequestMethod.GET)
    @ResponseBody
    public Object process(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        return ( ProcessInfo)request.getSession().getAttribute("proInfo");
    }  

    class ProcessInfo{
        public long totalSize = 1;
        public long readSize = 0;
        public String show = "";
        public int itemNum = 0;
        public int rate = 0;
    }  

}  

upload.jsp

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
<link href="http://cdn.bootcss.com/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="http://cdn.bootcss.com/bootstrap/2.3.2/css/bootstrap-responsive.min.css" rel="stylesheet">
</head>
<body>
		<form id='fForm' class="form-actions form-horizontal" action="uploadfile2"
		      encType="multipart/form-data" target="uploadf" method="post">
				 <div class="control-group">
					<label class="control-label">上传文件:</label>
					<div class="controls">
						<input type="file" id="file" name="file" style="width:550">

					</div>
					<div class="controls">
						<input type="file"  name="file" style="width:550">
					</div>
					<div class="controls">
						<input type="file"  name="file" style="width:550">
					</div>
					<label class="control-label">上传进度:</label>
					<div class="controls">
						<div  class="progress progress-success progress-striped" style="width:50%">
							<div  id = 'proBar' class="bar" style="width: 0%"></div>
						</div>
					</div>
				</div>

				 <div class="control-group">
					<div class="controls">
					<button type="button" id="subbut" class="btn">submit</button>
					</div>
				</div>
		</form>
		<iframe name="uploadf" style="display:none"></iframe>
</body>
</html>
<script type="text/javascript">

	$(document).ready(function() {
		$('#subbut').bind('click', function() {
			$('#fForm').submit();
			var eventFun = function() {
				$.ajax({
					type : 'GET',
					url : 'process',
					data : {},
					dataType : 'json',
					success : function(data) {
						$('#proBar').css

						('width', data.rate + '' + '%');
						$('#proBar').empty();
						$('#proBar').append(data.show);
						if (data.rate == 100) {
							window.clearInterval(intId);
						}
					}
				});
			};
			var intId = window.setInterval(eventFun, 500);
		});
	});
</script>
时间: 2024-12-13 23:02:19

SpringMVC上传文件进度显示的相关文章

Ajax上传文件进度条显示

要实现进度条的显示,就要知道两个参数,上传的大小和总文件的大小 html5提供了一个上传过程事件,在上传过程中不断触发,然后用已上传的大 小/总大小,计算上传的百分比,然后用这个百分比控制div框的显示,就可以 实现上传的进度条效果 前端页面 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax上传文件进度条显示

SpringMVC上传文件的三种解析方式

springMVC上传文件后,在action解析file文件的三种方式. jsp页面的写法: <form action="parserUploadFile1" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit"

2. SpringMVC 上传文件操作

1.创建java web项目:SpringMVCUploadDownFile 2.在项目的WebRoot下的WEB-INF的lib包下添加如下jar文件 1 com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar 2 com.springsource.net.sf.cglib-2.2.0.jar 3 com.springsource.org.aopalliance-1.0.0.jar 4 com.springsource.org.apache.commo

springmvc 上传文件时的错误

使用springmvc上传文件一直失败,文件参数一直为null, 原来是配置文件没写成功. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 最大上传尺寸 B单位 1M= 1024*1024 --> <property name="maxUploadSize&

springmvc上传文件,抄别人的

SpringMVC中的文件上传 分类: SpringMVC 2012-05-17 12:55 26426人阅读 评论(13) 收藏 举报 stringuserinputclassencoding 这是用的是SpringMVC-3.1.1.commons-fileupload-1.2.2和io-2.0.1 首先是web.xml [html] view plaincopyprint? <?xml version="1.0" encoding="UTF-8"?>

SpringMVC上传文件总结

如果是maven项目 需要在pom.xml文件里面引入下面两个jar包 <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>com

springmvc 上传文件的问题

今天用springmvc 上传文件的时候 报错 org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest 网上查找原因 说的有如下几种: 1.表单form 上没有 enctype="multipart/form-data"   这个属性 2.配置文件: <bean id="multi

SpringMVC上传文件(图片)并保存到本地

SpringMVC上传文件(图片)并保存到本地 小记一波~ 基本的MVC配置就不展示了,这里给出核心代码 在spring-mvc的配置文件中写入如下配置 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize">

SpringMVC上传文件的三种方式(转载)

直接上代码吧,大伙一看便知 这时:commonsmultipartresolver 的源码,可以研究一下 http://www.verysource.com/code/2337329_1/commonsmultipartresolver.java.html 前台: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <%@ page language="java" contentTy