2024年最全JavaWeb学习笔记4——带进度条的文件上传,看这一篇就够了

最后

作为过来人,小编是整理了很多进阶架构视频资料、面试文档以及PDF的学习资料,针对上面一套系统大纲小编也有对应的相关进阶架构视频资料


本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

需要这份系统化的资料的朋友,可以点击这里获取

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;

}

}

监听和读取上传进度

上传文件是用的doPost()方法,读取上传进度用doGet()方法。

ProgressUploadServlet.java的代码

package com.test.progressUpload;

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.Iterator;

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.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ProgressUploadServlet extends HttpServlet {

/**

  • Constructor of the object.

*/

public ProgressUploadServlet() {

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);

UploadStatus status =(UploadStatus)request.getSession(true).getAttribute(“uploadStatus”); //从Session读取数据

if(status==null){

response.getWriter().println(“没有上传的信息”);

return;

}

//各种上传信息

long startTime=status.getStartTime();

long currentTime=System.currentTimeMillis();

long time =(currentTime-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;

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

*/

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

UploadStatus status =new UploadStatus();

UploadListener listener =new UploadListener(status);

request.getSession(true).setAttribute(“uploadStatus”, status); //把状态放到Session里

ServletFileUpload upload =new ServletFileUpload(new DiskFileItemFactory()); //解析

upload.setProgressListener(listener);

try{

List itemList =upload.parseRequest(request); //提交的所有参数

for(Iterator it = itemList.iterator();it.hasNext()😉{

FileItem item =(FileItem) it.next();

if(item.isFormField()){ //如果是表单数据

System.out.println(“FormField:”+item.getFieldName()+“=”+item.getString());

}else { //否则是文件

System.out.println(“File:”+item.getName());

String fileName =item.getName().replace(“/”, “\”);

fileName =fileName.substring(fileName.lastIndexOf(“\”));

File saved =new File(“G:\upload_test”,fileName);

saved.getParentFile().mkdirs(); //保证路径存在

InputStream ins =item.getInputStream();

OutputStream ous =new FileOutputStream(saved);

//缓存写入

byte[] tmp =new byte[1024];

int len=-1;

while((len=ins.read(tmp))!=-1){

ous.write(tmp,0,len);

}

ous.close();

ins.close();

response.getWriter().println(“已保存文件:”+saved);

}

}

}catch(Exception e){

response.getWriter().println("上传发生错误: "+e.getMessage());

}

}

/**

  • Initialization of the servlet.

  • @throws ServletException if an error occurs

*/

public void init() throws ServletException {

// Put your code here

}

}

显示上传进度

ProgressUpload.jsp的代码

<%@ page language=“java” contentType=“text/html; charset=UTF-8”%>

Insert title here




面试结束复盘查漏补缺

每次面试都是检验自己知识与技术实力的一次机会,面试结束后建议大家及时总结复盘,查漏补缺,然后有针对性地进行学习,既能提高下一场面试的成功概率,还能增加自己的技术知识栈储备,可谓是一举两得。

以下最新总结的阿里P6资深Java必考题范围和答案,包含最全MySQL、Redis、Java并发编程等等面试题和答案,用于参考~

重要的事说三遍,关注+关注+关注!

历经30天,说说我的支付宝4面+美团4面+拼多多四面,侥幸全获Offer

image.png

更多笔记分享

历经30天,说说我的支付宝4面+美团4面+拼多多四面,侥幸全获Offer

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

需要这份系统化的资料的朋友,可以点击这里获取

试结束后建议大家及时总结复盘,查漏补缺,然后有针对性地进行学习,既能提高下一场面试的成功概率,还能增加自己的技术知识栈储备,可谓是一举两得。

以下最新总结的阿里P6资深Java必考题范围和答案,包含最全MySQL、Redis、Java并发编程等等面试题和答案,用于参考~

重要的事说三遍,关注+关注+关注!

[外链图片转存中…(img-FXh7Ciro-1715076310089)]

[外链图片转存中…(img-0z8yE4VH-1715076310089)]

更多笔记分享

[外链图片转存中…(img-l9kqaz6t-1715076310089)]

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

需要这份系统化的资料的朋友,可以点击这里获取

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值