使用servlet实现简易上传文件(带进度条版本)

该博客详细介绍了如何使用Servlet实现一个简单的文件上传功能,并且集成进度条展示,涵盖了xml配置、上传状态记录、监听器、Servlet处理以及前端JSP页面的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图


xml配置文件


  

  
  
   
    
    
     This is the description of my J2EE component
    
    
    
     This is the display name of my J2EE component
    
    
    
     UploadServlet
    
    
    
     UploadServlet
    
  
   
  


  
   
    
    
     UploadServlet
    
    
    
     /UploadServlet
    
  
   

  


上传状态记录类uploadStatus

import org.omg.CORBA.LongHolder;


public class UploadStatus {
	private long bytesRead;
	private long contentLength;
	private int items;
	private long startTime=System.currentTimeMillis();
	public long getBytesRead() {
		return bytesRead;
	}
	public void setBytesRead(long bytesRead) {
		this.bytesRead = bytesRead;
	}
	public long getContentLength() {
		return contentLength;
	}
	public void setContentLength(long contentLength) {
		this.contentLength = contentLength;
	}
	public int getItems() {
		return items;
	}
	public void setItems(int items) {
		this.items = items;
	}
	public long getStartTime() {
		return startTime;
	}
	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}
	
}


上传监听器

import org.apache.commons.fileupload.ProgressListener;


public class UploadListener implements ProgressListener {
	private UploadStatus uploadStatus;
	public UploadListener(UploadStatus uploadStatus) {
		// TODO Auto-generated constructor stub
		this.uploadStatus=uploadStatus;
	}

	@Override
	public void update(long arg0, long arg1, int arg2) {
		// TODO Auto-generated method stub
		uploadStatus.setBytesRead(arg0);
		uploadStatus.setContentLength(arg1);
		uploadStatus.setItems(arg2);
	}

}

servlet文件

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

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

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


@SuppressWarnings("deprecation")
public class UploadServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UploadServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. 
*/ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //禁止浏览器缓存 response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragrma", "no-cache"); response.setDateHeader("Expires", 0); //获取session里面的上传状态属性,注意这里的getSession(true)括号里面是有true的 UploadStatus status=(UploadStatus) request.getSession(true).getAttribute("uploadStatus"); if(status==null) { response.getWriter().println("没有传送消息"); return; } //以下是计算几个状态信息 long startTime=status.getStartTime(); long currTime=System.currentTimeMillis(); long time=(currTime-startTime)/1000+1; double velocity=((double)status.getBytesRead())/(double)time; double totaltime=status.getContentLength()/velocity; double timeLeft=totaltime-time; int percent=(int)(100*(double)status.getBytesRead()/(double)status.getContentLength()); double length=((double)status.getBytesRead())/1024/1024; double totalLength=((double)status.getContentLength())/1024/1024; //这里的"||"起到一个分隔符的作用,方便传到jsp文件时进行切割,详情请看jsp文件callback方法 String value=percent+"||"+length+"||"+totalLength+"||"+velocity+"||"+ time+"||"+totaltime+"||"+timeLeft+"||"+status.getItems(); response.getWriter().println(value); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ @SuppressWarnings({ "deprecation", "unchecked" }) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); request.setCharacterEncoding("utf-8"); //此处必须设置编码方式为GBK,否则会出现文件名、目录名或是卷标语法不正确的错误,使用utf-8也不行,其他编码方式未尝试过 response.setCharacterEncoding("GBK"); PrintWriter out=response.getWriter(); File file=null; UploadStatus uploadStatus=new UploadStatus(); //上传状态监听器 UploadListener listener=new UploadListener(uploadStatus); //把状态放到Session中,因为监听的原理是:服务器在处理上传文件的同时,将上传进度的信息例如 //文件的总长度、已上传多少等写入到Session中,客户端浏览器利用Ajax技术再新开一个独立的线程 //从Session中获取上传进度信息,并显示在界面中。 request.getSession(true).setAttribute("uploadStatus", uploadStatus); //DiskFileUpload diskFileUpload=new DiskFileUpload(); ServletFileUpload upload=new ServletFileUpload(new DiskFileItemFactory()); upload.setProgressListener(listener); try { List fileItems=upload.parseRequest(request); for(FileItem item:fileItems) { if(item.isFormField()) { //文本域,此处不介意说明 } //文件域 else { //获取原始文件 file=new File(new String(item.getName().getBytes(),"GBK")); //输出原始文件路径,亲测file.getAbsolutePath()不能正确输出全路径 out.println("文件客户端位置:"+file.getCanonicalPath()+"
"); //输出文件路径,此处设置为D盘下,可随意更改 File file1=new File("D:\\",file.getName()); //创建文件夹 file1.getParentFile().mkdir(); //创建文件 file1.createNewFile(); InputStream inputStream=item.getInputStream(); OutputStream outputStream=new FileOutputStream(file1); try{ byte [] b=new byte[1024]; int len=0; while((len=inputStream.read(b))>-1) { outputStream.write(b,0,len); } out.println("已保存文件在"+file1.getAbsolutePath()+"
"); }finally{ inputStream.close(); outputStream.close(); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); out.println("wrong"); } out.println("解析完毕"); out.flush(); out.close(); } /** * Initialization of the servlet.
* * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }


jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    uploadFile
	
  
	
  
	
      
	
  
	
  
	
  
	
  
  
  
   name="uploadiframe" width=0 height=0>
  
  
  	
  
上传文件
上传文件名称:
对于文件的描述:



文件下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值