ServletFileUpload上传文件带进度条

ServletFileUpload上传文件带进度条ServletUpload,文件上传,带进度条

ServletFileUpload上传文件带进度条

   涉及了两个架包:commons-io-2.0.1.jar,commons-fileupload-1.2.2.jar,还有一个jquery-2.2.4-min.js(下载链接:http://jquery.com/download/

  1. 文件上传页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  <script type="text/javascript"  src="${pageContext.request.contextPath}/js/jquery-2.2.4.min.js"></script>
  <script type="text/javascript">
       var progress;
       var uploadProcessTimer = null;
       
        function formSubmit(){  
           uploadProcessTimer =window.setInterval("getFileUploadProcess()",100);//每隔100毫秒执行callback
           document.forms[0].submit();
        }  
         function getFileUploadProcess() {  
              $.ajax({
	                 type:"GET",
	                 url:"servlet/fileUploadStatusServlet",
	                 dataType:"text",
	                 cache:false,
	                 success:function(data){
	                        
	                         
	                     if(data=="100%"){
	                         window.clearInterval(uploadProcessTimer);
	                     }else{
    				          progress=data;
	                         $("#show").width(data);
	                         $("#msg").text(data);
	                     }
	                 }
             });
          };
      
  </script>
  <body>
    <form action="${pageContext.request.contextPath}/servlet/fileUploadServlet" method="post" enctype="multipart/form-data">
      <input type="file" name="file">
     <!--  <input type="submit" value="上传"> -->
     <input type="button"  οnclick="formSubmit()" value="上传"/>
    </form>
    <div style="width:273px;">
   	 <div id="show" style="background:#0ff;height:26px;width:0%;"></div>
    </div>
    <span id="msg"></span>
  </body>

2.web.xml文件的配置

注意:servllet中servlet-name应该和servlet-mappiing中servlet-name要一致

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    
    <servlet>
     <servlet-name>servlet</servlet-name>
     <servlet-class>cn.ecit.test.fileUploadServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
      <servlet-name>servlet</servlet-name>
      <url-pattern>/servlet/fileUploadServlet</url-pattern>
    </servlet-mapping>
    
     <servlet>
     <servlet-name>StatuServlet</servlet-name>
     <servlet-class>cn.ecit.test.fileUploadStatusServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
      <servlet-name>StatuServlet</servlet-name>
      <url-pattern>/servlet/fileUploadStatusServlet</url-pattern>
    </servlet-mapping>
</web-app>

3.文件上传类

涉及了:ServletFileUpload,DiskFileItemFactory等,还按照日期来建文件夹,同时对上传文件进行换名称,以防重复不能上传相同文件。

package cn.ecit.xtzs.test;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class fileUploadServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 doPost(request,response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	    
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//获取日期格式
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM");
		String dirPath=sdf.format(new Date());
		
		 //保存的文件的路径
		String savePath=getServletContext().getRealPath("/upload/"+dirPath);
		
		
		File saveDir=new File(savePath);
		if(!saveDir.exists())
		{
			saveDir.mkdirs();
		}
		
		DiskFileItemFactory factory= new DiskFileItemFactory();
		
		//临时文件暂存的路径
		File tmpFile = new File(getServletContext().getRealPath("/WEB-INF/")+"/tmp");
		
		if(!tmpFile.exists())
		{
			tmpFile.mkdir();
		}
		//缓存临时文件
		factory.setRepository(tmpFile);
		
		ServletFileUpload sfu= new ServletFileUpload(factory);
		
		
		//文件上传的编码格式
		sfu.setHeaderEncoding("utf-8");
		//上传的文件总内存
		long maxSize = (long)1024*1024*1024*5;
		//单文件的最大内存
		long fileMaxSize = (long)1024*1024*1024*5;
		

		sfu.setFileSizeMax(maxSize);
		
		sfu.setSizeMax(fileMaxSize);
		
		//文件上传进度的监听
		UploadProgressListener listener=new UploadProgressListener(request);
	
		
		sfu.setProgressListener(listener);
		
		try{
		
			List<FileItem> itemlist=sfu.parseRequest(request);
			for(FileItem fileItem:itemlist)
			{
				String fieldName=fileItem.getFieldName();
				System.out.println("控件 称"+fieldName);
				if(fileItem.isFormField())
				{
					String value=fileItem.getString();
					value=new String(value.getBytes("iso8859-1"),"utf-8");
					System.out.println("普通内容:"+fieldName+"值为:"+value);
				}else{
					//文件大小
					Long size=fileItem.getSize();
					//文件名字
					String fileName=fileItem.getName();
					String newFileName=UUID.randomUUID().toString().replaceAll("-","")+fileName.substring(fileName.lastIndexOf("."));
					System.out.println("文件名:"+newFileName+"文件大小:"+size);
					
					File file=new File(savePath,newFileName);
					fileItem.write(file);
				}	
				
			}
			request.getRequestDispatcher("/success.jsp").forward(request, response);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	
	}

}

4.文件获取进度信息类

通过session来获取设置的文件上传的信息,还要通过PrintWriter来响应页面响应的请求返回数据给页面;记得关闭写入流。

package cn.ecit.xtzs.test;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * 文件上传进度状态类
 * @author 
 *
 */

public class fileUploadStatusServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		doPost(request,response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");  
        
        HttpSession session=request.getSession();
        
        Object status = session.getAttribute("key");//获取上传进度百分比 
        if(status==null) return;  
        PrintWriter out = response.getWriter();  
        out.write(status.toString());
        out.flush();
        out.close();
		
	}

}

5.文件进度监听类

package cn.ecit.xtzs.test;

import java.text.NumberFormat;

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

import org.apache.commons.fileupload.ProgressListener;

public class UploadProgressListener implements ProgressListener {
    
    private HttpSession session;
	private long kiloBytes=-1;
	
    public UploadProgressListener(HttpServletRequest request) {
		
		this.session = request.getSession();
	}

    @Override
	//pBytes
	public void update(long PBytesRead, long PContentLength, int PItems) {
	
		Long KBytes=PBytesRead/1024;
		if(kiloBytes==KBytes)
		{
			return;
		}
		kiloBytes=KBytes;
		System.out.println("正在读取项目"+KBytes);
		if(PContentLength==-1)
		{
			System.out.println("目前已经读取了"+PBytesRead+"字节数据");
		}
		else
		{
			System.out.println("目前已经读取了"+PContentLength+"中的"+PBytesRead+"字节数据");
		}
		//获取上传进度的百分比
		double read=((double)KBytes)/(PContentLength/1024);
		
		
		NumberFormat nf=NumberFormat.getPercentInstance();
		
		session.setAttribute("key", nf.format(read));
		
		System.out.println("进度时间:"+nf.format(read));
		
	}

6.效果图:

<img src="https://img-blog.csdn.net/20160729161453382" alt="" />

今天的文章ServletFileUpload上传文件带进度条分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/13259.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注