文件上传(无刷新,带进度条,带网速)下载完整

  • 作者: 凯哥Java(公众号:凯哥Java)
  • 工作小总结
  • 时间:2022-02-19 00:44
  • 2879人已阅读
简介 有时候,我们需要上传的时候返回上传进度条及显示上传速度。本文咱们就简单的以servlet及jsp来个小demo

🔔🔔🔔好消息!好消息!🔔🔔🔔

有需要的朋友👉:联系凯哥 微信号 kaigejava2022

该程序主要解决带进度,无刷新,带网速计算的上传功能,简单明了,不过是本人愚拙的做法,若有更好的做法介绍介绍

java文件:

package com.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

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

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class Upload extends HttpServlet {
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("application/xml");
		final PrintWriter out=resp.getWriter();
		XMLOutputter pw=new XMLOutputter(Format.getPrettyFormat().setEncoding("iso-8859-1"));
		Document doc=(Document)req.getSession().getAttribute("msg"+req.getSession().getId())==null?new Document():(Document)req.getSession().getAttribute("msg"+req.getSession().getId());
		pw.output(doc,out);
		System.out.println(req.getSession().getAttribute("msg"+req.getSession().getId()));
	}

	public void doPost(final HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		final PrintWriter out=response.getWriter();
		ServletFileUpload upload = new ServletFileUpload();
		upload.setSizeMax(100*1024*1024);
		ProgressListener progressListener = new ProgressListener(){
			   long lastBytes=0;
			   long lastTime=System.currentTimeMillis();
			   public void update(long pBytesRead, long pContentLength, int pItems) {
			       if (pContentLength == -1) {
			           System.out.println("So far, " + pBytesRead + " bytes have been read.");
			       } else {
			           long stepByte=(pBytesRead-lastBytes)/1024;
			           String bit="";
			           double stepTime=0f;
			           stepTime=(double) ((System.currentTimeMillis()-lastTime)/1000.0);
			           bit=Math.round(stepByte/stepTime)+"KB/S";
			           Document doc=new Document();
			           Element root=new Element("root");
			           doc.addContent(root);
			           Element file=new Element("file");
			           file.setAttribute("id",pItems+"");
			           file.setAttribute("uploadBytes", pBytesRead+"");
			           file.setAttribute("totalBtyes", pContentLength+"");
			           file.setAttribute("bit", bit);
			           root.addContent(file);
			           request.getSession().setAttribute("msg"+request.getSession().getId(), doc);
			       }
			   }
			};
		upload.setProgressListener(progressListener);
		try {
			FileItemIterator iter = upload.getItemIterator(request);
			while (iter.hasNext()) {
			    FileItemStream item = iter.next();
				InputStream stream = item.openStream();
		    if (item.isFormField()) {
		    } else {
		    	int tmp=item.getName().lastIndexOf("\\")==-1?0:item.getName().lastIndexOf("\\");
		    	if(item.getName().substring(tmp)!=null&&!item.getName().substring(tmp).equals("")){
		    	String fileName="D:\\upload\\"+item.getName().substring(tmp);
		        FileOutputStream tempFile=new FileOutputStream(fileName); 
		        int  buf;
		        while((buf=stream.read())!=-1){
		        	tempFile.write(buf);
		        	tempFile.flush();
		        	}
		        tempFile.close();
		    	}
		    }
		}} catch (FileUploadException e) {
			e.printStackTrace();
		}
		
		
		out.close();
	}
}



jsp文件:

<%@ page language="java" contentType="text/html; charset=gb2312" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<title>带进度的文件上传</title>
</head>    
<body>    
<div style="width:500px; margin:0 auto;">
<form action="servlet/Upload" id="form1" name="form1" encType="multipart/form-data"  method="post" target="hidden_frame" οnsubmit="checkUpload();">    
    <input type="file" id="file1" name="file1" style="width:450"/>
    <input type="submit" value="上传文件"/>                       
</form>  
</div>  
<iframe name="hidden_frame" id="hidden_frame" style="display: none;"></iframe>
<div  style="width: 500px;height:80px;margin:auto;text-align: center;">
	<div id="msg" style="float: right;"></div>
	<div id="process" style="background-image: url(progress-bg.gif);width: 0px;height: 20px;background-repeat: repeat-x"></div>
	</div>  
</body>    
</html>    
<script type="text/javascript">   
	var startTimer; 
	function checkUpload(){
		 startTimer=setInterval(function(){
		 $.ajax({url: "servlet/Upload?ran="+Math.random(),dataType :"xml",success:callback});
		},1000);
	}
    function callback(msg)    
	{   
	var node=$(msg).find("file");
	var uploadBytes=parseInt(node.attr("uploadBytes"));
	var totalBtyes=parseInt(node.attr("totalBtyes"));
	var bit=node.attr("bit");
	var percentage=Math.round(uploadBytes/totalBtyes*100);
	tmp="已上传"+percentage+"%  网速:"+bit;
	var wid=parseInt(uploadBytes/totalBtyes)*300;
	$("#process").css("width",percentage+"%");  
    $("#msg").html("<font color=red>"+tmp+"</font>");
	if(percentage==100){
			if(startTimer!=null){
				clearInterval(startTimer);
			}
			}
	}
</script>





————————————————
版权声明:本文为CSDN博主「lyon-yao」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq378741744/article/details/83889303


TopTop