Home Web Front-end HTML Tutorial How to display the HTML5 Ajax file upload progress bar

How to display the HTML5 Ajax file upload progress bar

Jan 10, 2018 am 09:58 AM
ajax h5 html5

This article mainly introduces HTML5 AjaxFile uploadHow the progress bar is displayed. It is based on native HTML5 implementation and does not require falsh support. The progress can be customized and displayed, and the control is flexible. , friends who are interested in HTML5 upload progress bar can refer to

I originally planned to use jquery plug-in for asynchronous file upload, such as uploadfy, but it needs additional support. Some people use iframe to imitate the asynchronous upload mechanism, which feels like Rather 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(&#39;fileName&#39;).files[0];
  if (file) {
   var fileSize = 0;
   if (file.size > 1024 * 1024)
   fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + &#39;MB&#39;;
   else
   fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + &#39;KB&#39;;

   document.getElementById(&#39;fileName&#39;).innerHTML = &#39;Name: &#39; + file.name;
   document.getElementById(&#39;fileSize&#39;).innerHTML = &#39;Size: &#39; + fileSize;
   document.getElementById(&#39;fileType&#39;).innerHTML = &#39;Type: &#39; + file.type;
  }
  }
 
 //上传文件
 function uploadFile() {
  var fd = new FormData();
  //关联表单数据,可以是自定义参数
  fd.append("name", document.getElementById(&#39;name&#39;).value);
  fd.append("fileName", document.getElementById(&#39;fileName&#39;).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(&#39;progressNumber&#39;).innerHTML = percentComplete.toString() + &#39;%&#39;;
  }
  else {
   document.getElementById(&#39;progressNumber&#39;).innerHTML = &#39;unable to compute&#39;;
  }
 }

 //上传成功响应
 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

The above is all the content of this article, I hope it will be useful for everyone to learn help! !

Related recommendations:

How to implement HTML5 brick-breaking game using native js

Ajax implementation of flicker-free scheduled refresh page example code

Questions about the use of get and post in Ajax

The above is the detailed content of How to display the HTML5 Ajax file upload progress bar. 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)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles