search
HomeWeb Front-endJS TutorialImplement file upload and display progress bar based on ajax_javascript skills

下面给大家分享下基于ajax实现文件上传并显示进度条。在jsp部分,需要设计一个表单,form的属性添加 enctype="multipart/form-data",设计一个iframe,作为隐藏。form的target等于iframe的name;

在servlet部分:文件上传用的Commons-FileupLoad,需要两个Jar,commons-fileupload和commons-io,少了第二个会报出找不到类的异常;

第一个servlet处理上传,及把上传进度保存到session,第二个servlet处理ajax请求,回传session保存的进度值;

进度条:可以用ajax拿到回传的进度值,改变图片的width实现变化;

jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="css/progress.css">
<script type="text/javascript" src="js/ul.js" charset="gbk"></script>
</head>
<body>
<form action="UploadServlet" name="f1" id="f1" method="post" enctype="multipart/form-data" target="if">
 <input type="file" name="file1" /><br><br>
 <input type="reset" name="res1" value="重置"/>
 <input type="button" name="but1" value="提交" onclick="go();"/>
</form><br>
<div id="pro" class="pro" align="left">
 <img src="/static/imghwm/default1.png"  data-src="photo/progress.png"  class="lazy"  alt=""    style="max-width:90%"  style="max-width:90%" id="imgpro">
</div>
  <span id="prop" style="width:15px;height:15px;display: none;">0%</span>
<iframe id="if" name="if" src="" style="display: none"></iframe>
</body>
</html>

这是index.jsp里的代码:

提交后还在当前页显示进度,所以要用到iframe,提交后的返回放到隐藏的iframe里,不影响页面效果;

css代码:

复制代码 代码如下:

.pro{
  height:15px;
  width:500px;
  background: #FFFFF0;
  border: 1px solid #8FBC8F;
  margin: 0;
  padding: 0;
  display:none;
  position: relative;
  left:25px;
  float:left;
}

js代码

function go(){
 f1.submit();
 document.getElementById("pro").style.display="block";
 document.getElementById("prop").style.display="";
 timer=setInterval("getP()",50);
 
}

var xmlHttpRequest;
function getP(){
 
 if(window.XmlHttpRequest){
  xmlHttpRequest=new XmlHttpRequest();
 }else{
  xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
 } 
 
 xmlHttpRequest.onreadystatechange=callBack; 
 url="getProgressServlet";
 xmlHttpRequest.open("post",url,true);
 
 xmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xmlHttpRequest.send("&timeStamp="+(new Date()).getTime()); 
 
}
//回调函数
function callBack(){
 
 if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){ 
  
  result=xmlHttpRequest.responseText;
  var result=result.replace(/(^\s*)|(\s*$)/g, "");
  var res=result.split(",");
  var flag=res[1]; 
  var per=parseInt(res[0]);
  var err=res[2];
  document.getElementById("imgpro").style.width=per*5+"px";
  document.getElementById("prop").innerHTML=per+"%";
  if(flag=="OK"){
   window.clearInterval(timer);
   alert("上传成功!");
   document.getElementById("pro").style.display="none";
   document.getElementById("prop").innerHTML="";
   f1.reset();
  }
  if(err!=""||err.length>0){
   window.clearInterval(timer);
   alert(err);
  }
  if(flag==null){
   window.clearInterval(timer);
  }
 }
}

flag为上传成功标记,err为出错标记;

servlet代码(UploadServlet):

package com.ul.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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 javax.servlet.http.HttpSession;

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


public class UploadServlet extends HttpServlet {
 
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response); 
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //设置编码格式为utf-8
  request.setCharacterEncoding("utf-8");
  response.setCharacterEncoding("utf-8"); 
  //获取session,保存进度和上传结果,上传结果初始值为NOK,当为Ok表示上传完成
  HttpSession session=request.getSession();
  session.setAttribute("prog", "0");
  session.setAttribute("result", "NOK"); 
  session.setAttribute("error", "");
  String error="";
  //给上传的文件设一个最大值,这里是不得超过50MB
  int maxSize=50*1024*1024;
  //创建工厂对象和文件上传对象
  DiskFileItemFactory factory=new DiskFileItemFactory();
  ServletFileUpload upload=new ServletFileUpload(factory);
  try {
   //解析上传请求
   List items=upload.parseRequest(request);
   Iterator itr=items.iterator();
   
   while(itr.hasNext()){
    FileItem item=(FileItem)itr.next();
    //判断是否为文件域
    if(!item.isFormField()){
     if(item.getName()!=null&&!item.getName().equals("")){
      //获取上传文件大小和文件名称
      long upFileSize=item.getSize();   
      String fileName=item.getName();
      if(upFileSize>maxSize){
       error="您上传的文件太大了,请选择不超过50MB的文件!";
       break;
      }
      //此时文件暂存在服务器的内存中,构造临时对象
      File tempFile=new File(fileName);
      //指定文件上传服务器的目录及文件名称
      File file=new File("f:\\temp",tempFile.getName());
      //构造输入流读文件
      InputStream is=item.getInputStream();
      int length=0;
      byte[] by=new byte[1024];
      double persent=0;
      FileOutputStream fos=new FileOutputStream(file);
      PrintWriter out=response.getWriter();
      while((length=is.read(by))!=-1){
       //计算文件进度
       persent+=length/(double)upFileSize*100D;
       fos.write(by, 0, length);
       session.setAttribute("prog", Math.round(persent)+""); 
       Thread.sleep(10);
      }
      fos.close();
      Thread.sleep(1000);
     }else{
      error="没选择上传文件!";
     }
    }
   }
   
   
  } catch (Exception e) {
   e.printStackTrace();
   error="上传文件出现错误:"+e.getMessage();
  }
  if(!error.equals("")){ 
   session.setAttribute("error", error);
  }else{
   session.setAttribute("result", "OK");
  }
 }
}

不要忘记commons-io包

servlet代码(getProgressServlet):

package com.ul.servlet;

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;

public class getProgressServlet extends HttpServlet {
 
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response);
 }


 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  request.setCharacterEncoding("utf-8");
  response.setCharacterEncoding("utf-8");
  HttpSession sesson=request.getSession(); 
  PrintWriter out=response.getWriter(); 
  String str=(String)sesson.getAttribute("prog")+"";
  String res=(String)sesson.getAttribute("result");
  String err=(String)sesson.getAttribute("error");
  System.out.println(str+","+res+","+err);
  out.print(str+","+res+","+err);

  out.flush();
  out.close();
 }

}


效果图如下:

 

以上就是本文的全部内容,希望对大家有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)