⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 utilmethod.java

📁 前期开发时开发的新闻发布系统
💻 JAVA
字号:
package book.upload;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UtilMethod
{
	
	//获取上传信息(从Session中获取上传状态,将状态转化成进度条的方式返回给客户端)
	public static void doStatus(HttpSession session, HttpServletResponse response) throws IOException 
	{		
		//设置该响应不在缓存中读取
		response.addHeader("Expires", "0");
		response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.addHeader("Pragma", "no-cache");
		response.setCharacterEncoding("UTF-8");
        //获得保存在Session中的状态信息(因为Session在填充值的时候填充的是FileUploadStats类类型,故在取值时也要强制转化为FileUploadStats类类型)
		//因为FileUploadStats是UploadListener中的内部类,故要用UploadListener.FileUploadStats
		UploadListener.FileUploadStats fileUploadStats = (UploadListener.FileUploadStats) session.getAttribute("FILE_UPLOAD_STATS");
		if(fileUploadStats != null) 
		{
			long bytesProcessed = fileUploadStats.getBytesRead();//获得已经上传的数据大小
			long sizeTotal = fileUploadStats.getTotalSize();//获得上传文件的总大小
			if(sizeTotal > 200*1024)
			{
				response.getWriter().println("<b>上传文件超过指定大小!</b>");
				return;
			}
			//计算上传完成的百分比
			long percentComplete = (long) Math.floor(((double) bytesProcessed / (double) sizeTotal) * 100.0);
			//获得上传已用的时间
			long timeInSeconds = fileUploadStats.getElapsedTimeInSeconds();
			//计算平均上传速率
			double uploadRate = bytesProcessed / (timeInSeconds + 0.00001);
			//计算总共所需时间
			double estimatedRuntime = sizeTotal / (uploadRate + 0.00001);
            //将上传状态返回给客户端
			response.getWriter().println("<b>上传状态:</b><br/>");
			if(fileUploadStats.getBytesRead() != fileUploadStats.getTotalSize())//表示还没有上传完毕 
			{
				response.getWriter().println("<div class=\"prog-border\"><div class=\"prog-bar\" align=\"center\" style=\"width: " + percentComplete + "%;\">" + percentComplete + "%</div></div>");
				response.getWriter().println("已上传:" + bytesProcessed + "字节,总大小:" + sizeTotal + "字节,已完成:" + percentComplete + "%,平均上传速率:" + (long) Math.round(uploadRate / 1024) + " 字节/秒<br/>");
				response.getWriter().println("已用时:" + formatTime(timeInSeconds) + ",共需要:" + formatTime(estimatedRuntime) + ",还剩余" + formatTime(estimatedRuntime - timeInSeconds) + "<br/>");
			} 
			else//表示上传完毕
			{
				response.getWriter().println("已上传:" + bytesProcessed + "字节,总大小:" + sizeTotal + "字节<br/>");
				response.getWriter().println("完毕<br/>");
			}
		}
        //如果文件已经上传完毕
		if(fileUploadStats != null && fileUploadStats.getBytesRead() == fileUploadStats.getTotalSize()) 
		{
			response.getWriter().println("<b>上传完毕</b>");
		}
	}
	
	//显示时间的封装方法
	public static String formatTime(double timeInSeconds) 
	{		
		long seconds = (long) Math.floor(timeInSeconds);
		long minutes = (long) Math.floor(timeInSeconds / 60.0);
		long hours = (long) Math.floor(minutes / 60.0);
		if(hours != 0) 
		{
			return hours + "小时" + (minutes % 60) + "分" + (seconds % 60) + "秒";
		} 
		else if(minutes % 60 != 0) 
		{
			return (minutes % 60) + "分" + (seconds % 60) + "秒";
		} 
		else 
		{
			return (seconds % 60) + " 秒";
		}
	}
	
	//上传文件处理过程(通过监听器类UploadListener对上传状态进行监听)
	public static List doFileUpload(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException 
	{	
		List items = null;
		try 
		{
			//创建UploadListener监听器对象
			UploadListener listener = new UploadListener(request.getContentLength());
			listener.start();//启动监听状态
			//将监听器对象的状态保存在Session中
			session.setAttribute("FILE_UPLOAD_STATS",  listener.getFileUploadStats());
			//创建MonitoredDiskFileItemFactory对象(其中FileItemFactory是org.apache.commons.fileupload包中的一个接口)
			FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
			//通过该工厂对象创建ServletFileUpload对象(其中ServletFileUpload是org.apache.commons.fileupload.servlet包中的一个类)
			ServletFileUpload upload = new ServletFileUpload(factory);
			//将转化请求保存到List对象中
			items = upload.parseRequest(request);
			//停止使用监听器
			listener.done();
			boolean hasError = false;
			//循环items中的对象
			for(Iterator i = items.iterator(); i.hasNext();) 
			{
				//(主要是涉及到上传文件中有可能同时上传多个文件,但最终服务器只会将其看作一个数据流,并不能区分开来,故要将数据转化成单个条目(即FileItem))
				//其中FileItem是org.apache.commons.fileupload包中的一个接口
				FileItem fileItem = (FileItem) i.next();
				if(!fileItem.isFormField())//如果该FileItem不是表单域 
				{
					processUploadedFile(fileItem, session);//调用processUploadedFile方法,将数据保存到文件中
					fileItem.delete();//内存中删除该数据流
				}
			}
			if(!hasError)//如果没有出现错误 
			{
				sendCompleteResponse(response, null);//调用sendCompleteResponse方法
			} 
			else 
			{
				sendCompleteResponse(response, "不能执行上传,请查看详细日志信息!!!");
			}
		} 
		catch(Exception e) 
		{
			sendCompleteResponse(response, e.getMessage());
		}
		return items;
	}
	
	//将内存中的数据保存到硬盘中
	public static void processUploadedFile(FileItem item,HttpSession sessioin) 
	{		
		//获得上传文件的文件名
		String fileName = item.getName().substring(item.getName().lastIndexOf("\\") + 1);		
		//创建File对象,将上传的文件保存到指定的文件夹下
		String path = sessioin.getAttribute("url").toString();
		File file = new File(path, fileName);
		InputStream in = null;
		FileOutputStream out = null;
		try 
		{
			in = item.getInputStream();//获得输入数据流文件
			//将该数据流写入到指定文件中
			out = new FileOutputStream(file);
			byte[] buffer = new byte[4096]; // To hold file contents
			int bytes_read;
			while((bytes_read = in.read(buffer)) != -1)// Read until EOF 
			{
				out.write(buffer, 0, bytes_read);
			}
		} 
		catch(IOException e1) 
		{
			e1.printStackTrace();
		}
		finally
		{
			if(in != null)
			{
				try 
				{
					in.close();
				} 
				catch(IOException e) 
				{
					e.printStackTrace();
				}
			}
			if(out != null)
			{
				try 
				{
					out.close();
				} 
				catch(IOException e) 
				{
					e.printStackTrace();
				}				
			}							
		}
	}
	
	//将信息返回给客户端(因为此时返回给客户端的是隐藏中<iframe>网页中的代码,所以要调用父窗口中的killUpdate()方法)
	public static void sendCompleteResponse(HttpServletResponse response, String message) throws IOException 
	{		
		if(message == null)//表示上传过程中没有出现错误 
		{
			response.getOutputStream().print("<html><head><script type='text/javascript'>function killUpdate() { window.parent.killUpdate(''); }</script></head><body onload='killUpdate()'></body></html>");
		} 
		else 
		{
			response.getOutputStream().print("<html><head><script type='text/javascript'>function killUpdate() { window.parent.killUpdate(' "+ message + " '); }</script></head><body onload='killUpdate()'></body></html>");
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -