Home Web Front-end JS Tutorial HTML5+Ajax file upload progress bar display (detailed graphic and text explanation)

HTML5+Ajax file upload progress bar display (detailed graphic and text explanation)

Apr 04, 2018 pm 04:33 PM
h5 show

This time I will bring you HTML5+AjaxFile uploadProgress bardisplay (detailed graphic and text explanation), HTML5+Ajax file upload progress bar displayNotesWhat are they? The following is a practical case. Let’s take a look.

Originally planned to use jquery plug-in for asynchronous file upload, such as uploadfy, but it needs additional support. Some people also use iframe to imitate the asynchronous upload mechanism, which feels awkward. Because the project does not consider lower version browsers, it was decided to use HTML5 for implementation. The following is just a simple demo, you need to make the specific style yourself.
The background is based on strut2 for file processing, which depends on the project. Just be careful about setting file size limits. This configuration is set according to the specific situation. If it exceeds this value, 404 will be reported.
The first is the upload page, which is relatively simple and comes with the file. or this parameter.

upload.jsp

<%@page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> 
<%
String path = request.getContextPath(); 
%>
<!DOCTYPE html>
<html>
<head>
 <title>使用XMLHttpRequest上传文件</title>
 <script type="text/javascript">
 var xhr = new XMLHttpRequest();
 
 //监听选择文件信息
 function fileSelected() {
  //HTML5文件API操作
  var file = document.getElementById('fileName').files[0];
  if (file) {
   var fileSize = 0;
   if (file.size > 1024 * 1024)
   fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
   else
   fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
   document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
   document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
   document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
  }
  }
 
 //上传文件
 function uploadFile() {
  var fd = new FormData();
  //关联表单数据,可以是自定义参数
  fd.append("name", document.getElementById('name').value);
  fd.append("fileName", document.getElementById('fileName').files[0]);
  //监听事件
  xhr.upload.addEventListener("progress", uploadProgress, false);
  xhr.addEventListener("load", uploadComplete, false);
  xhr.addEventListener("error", uploadFailed, false);
  xhr.addEventListener("abort", uploadCanceled, false);
  //发送文件和表单自定义参数
  xhr.open("POST", "<%=path%>/user/uploadifyTest_doUpload");
  xhr.send(fd);
  }
 //取消上传
 function cancleUploadFile(){
 xhr.abort();
 }
 
 //上传进度
 function uploadProgress(evt) {
  if (evt.lengthComputable) {
   var percentComplete = Math.round(evt.loaded * 100 / evt.total);
   document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
  }
  else {
   document.getElementById('progressNumber').innerHTML = 'unable to compute';
  }
 }
 //上传成功响应
 function uploadComplete(evt) {
  //服务断接收完文件返回的结果
  alert(evt.target.responseText);
 }
 
 //上传失败
 function uploadFailed(evt) {
  alert("上传失败");
 }
 //取消上传
 function uploadCanceled(evt) {
  alert("您取消了本次上传.");
 }
 </script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="upload.php">
<p class="row">
  <label for="fileToUpload">选择文件</label>
<input type="file" name="fileName" id="fileName" onchange="fileSelected();"/>
 </p>
<p id="fileName"></p>
<p id="fileSize"></p>
<p id="fileType"></p>
<p class="row">
上传者:<input type="text" name="name" id="name"/>
<input type="button" onclick="uploadFile()" value="上传" />
<input type="button" onclick="cancleUploadFile()" value="取消" />
 </p>
<p id="progressNumber"></p>
</form>
</body>
</html>
Copy after login

fd.append("name", document.getElementById('name').value);
fd.append("fileName", document.getElementById('fileName').files[0]);
These two sentences bind data to the form. Because html5 supports multiple file uploads,
document.getElementById('fileName').files returns an array. There is only one file here so remove the element with index 0.

xhr.upload.addEventListener("progress", uploadProgress, false);

##xhr.addEventListener("load", uploadComplete, false);

xhr.addEventListener("error", uploadFailed, false);

xhr.addEventListener("abort", uploadCanceled, false);Bind progress, upload, error, and interruption events here to provide some interaction. The file progress is displayed in the progress callback. Then paste the background code and action configuration, UploadifyTestAction.java

package com.bjhit.eranges.actions.test;
import java.io.File;
import com.opensymphony.xwork2.ActionSupport;
public class UploadifyTestAction extends ActionSupport {
 private static final long serialVersionUID = 837481714629791752L;
 private File fileName;
 private String name;
 private String responseInfo;
 public String doUpload() throws Exception {
 System.out.println(name);
 File myFile = fileName;
 System.out.println(myFile.getName());
 responseInfo = "上传成功!";
 return "doUpload";
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public File getFileName() {
 return fileName;
 }
 public void setFileName(File fileName) {
 this.fileName = fileName;
 }
 public String getResponseInfo() {
 return responseInfo;
 }
 public void setResponseInfo(String responseInfo) {
 this.responseInfo = responseInfo;
 }
}
Copy after login
action configuration

<!-- 文件上传例子 -->
<action name="uploadifyTest_*" class="com.bjhit.eranges.actions.test.UploadifyTestAction" method="{1}">
 <result name="doUpload" type="json">
 <param name="includeProperties">responseInfo</param>
 <param name="excludeNullProperties">true</param>
 </result>
</action>
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese website Other related articles!

Recommended reading:

Methods for ajax to read Json data

Methods to construct AJAX to implement form JSON conversion

The above is the detailed content of HTML5+Ajax file upload progress bar display (detailed graphic and text explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove news and trending content from Windows 11 Search How to remove news and trending content from Windows 11 Search Oct 16, 2023 pm 08:13 PM

When you click the search field in Windows 11, the search interface automatically expands. It displays a list of recent programs on the left and web content on the right. Microsoft displays news and trending content there. Today's check promotes Bing's new DALL-E3 image generation feature, the "Chat Dragons with Bing" offer, more information about dragons, top news from the Web section, game recommendations, and the Trending Search section. The entire list of items is independent of your activity on your computer. While some users may appreciate the ability to view news, all of this is abundantly available elsewhere. Others may directly or indirectly classify it as promotion or even advertising. Microsoft uses interfaces to promote its own content,

iOS 17's standby mode turns a charging iPhone into a home hub iOS 17's standby mode turns a charging iPhone into a home hub Jun 06, 2023 am 08:20 AM

In iOS 17 Apple is introducing Standby Mode, a new display experience designed for charging iPhones in a horizontal orientation. In this position, the iPhone is able to display a series of full-screen widgets, turning it into a useful home hub. Standby mode automatically activates on an iPhone running iOS 17 placed horizontally on the charger. You can view time, weather, calendar, music controls, photos, and more. You can swipe left or right through the available standby options and then long press or swipe up/down to customize. For example, you can choose from analog view, digital view, bubble font, and daylight view, where the background color changes based on time as time passes. There are some options

Windows 11 User Guide: How to disable ad pop-ups Windows 11 User Guide: How to disable ad pop-ups Sep 22, 2023 pm 07:21 PM

Microsoft's Windows 11 operating system may periodically display suggestions as pop-ups on your computer using the notification system. The suggestions system, originally intended to provide users with tips and suggestions for improving their Windows 11 workflows, has almost completely transformed into an advertising system to promote Microsoft services and products. Suggestion pop-ups might advertise a Microsoft 365 subscription to users, suggest linking an Android phone to the device, or set up a backup solution. If these pop-ups annoy you, you can tweak your system to disable them entirely. The following guide provides recommendations on disabling pop-ups on devices running Microsoft’s Windows 11 operating system.

Reasons and solutions for desktop layout being locked Reasons and solutions for desktop layout being locked Feb 19, 2024 pm 06:08 PM

What happens when the desktop layout is locked? When using the computer, sometimes we may encounter the situation where the desktop layout is locked. This problem means that we cannot freely adjust the position of desktop icons or change the desktop background. So, what exactly is going on when it says that the desktop layout is locked? 1. Understand the desktop layout and locking functions. First, we need to understand the two concepts of desktop layout and desktop locking. Desktop layout refers to the arrangement of various elements on the desktop, including shortcuts, folders, widgets, etc. we can be free

How to turn on live captions instantly in Windows 11 How to turn on live captions instantly in Windows 11 Jun 27, 2023 am 08:33 AM

How to turn on live subtitles instantly in Windows 11 1. Press Ctrl+L on your keyboard 2. Click Agree 3. A popup will appear saying Ready to add subtitles in English (US) (depending on your preferred language) 4. Additionally, you can filter profanity by clicking the gear button? Preference? Filtering Swear Words Related Articles How to Fix Activation Error Code 0xc004f069 in Windows Server The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Pass these preliminary checks and if these checks do not

What does h5 mean? What does h5 mean? Aug 02, 2023 pm 01:52 PM

H5 refers to HTML5, the latest version of HTML. H5 is a powerful markup language that provides developers with more choices and creative space. Its emergence promotes the development of Web technology, making the interaction and effect of web pages more Excellent, as H5 technology gradually matures and becomes popular, I believe it will play an increasingly important role in the Internet world.

How to make a remote desktop connection display the other party's taskbar How to make a remote desktop connection display the other party's taskbar Jan 03, 2024 pm 12:49 PM

There are many users using Remote Desktop Connection. Many users will encounter some minor problems when using it, such as the other party's taskbar not being displayed. In fact, it is probably a problem with the other party's settings. Let's take a look at the solutions below. How to display the other party's taskbar during Remote Desktop Connection: 1. First, click "Settings". 2. Then open "Personalization". 3. Then select "Taskbar" on the left. 4. Turn off the Hide Taskbar option in the picture.

How to check the current directory in Linux? How to check the current directory in Linux? Feb 23, 2024 pm 05:54 PM

In Linux systems, you can use the pwd command to display the current path. The pwd command is the abbreviation of PrintWorkingDirectory and is used to display the path of the current working directory. Enter the following command in the terminal to display the current path: pwd After executing this command, the terminal will display the full path of the current working directory, such as: /home/user/Documents. In addition, you can use some other options to enhance the functionality of the pwd command. For example, the -P option can display

See all articles