《Layui宇宙版教程》提供2000人的QQ群进行交流学习,QQ群号:1046961650,或通过手机QQ扫描二维码进入:
1.25 上传upload
上传模块自Layui2.0的版本开始,进行了全面重写,这使得它的功能不再那么单一,它所包含的不仅是更为强劲的功能,还有灵活的UI。任何元素都可以作为上传组件来调用,譬如按钮、图片、普通的DIV等等,而不再是一个单调的file文件域。
模块加载名称:upload。
1.25.1 前端界面效果
测试代码如下:
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css" />
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#test1', //绑定元素
url: '/upload/', //上传接口
done: function(res) {
//上传完毕回调
alert("成功上传");
},
error: function() {
//请求异常回调
alert("上传失败");
}
});
script>
body>
html>
以上代码只是演示上传的前端界面,并没有后台支持,所以上传失败。
1.25.2 核心方法与基础参数选项
使用upload模块必须与upload.render(options)方法打交道,其中的options即为基础参数,它是一个对象,示例代码如图1-xx所示。
从Layui 2.1.0开始,允许直接在元素上设定基础参数,示例代码如图1-xx所示。
更多参数如图1-xx所示。
1.25.3 上传接口
设定一个URL地址给url参数,用来告诉upload模块的服务端上传接口,示例代码如图1-xx所示。
该接口返回的相应信息(response)必须是一个标准的JSON格式,示例代码如图1-xx所示。
注意1:不一定非得按照上述格式返回,只要是合法的JSON字符即可。其响应信息会转化成JS对象传递给done回调。
注意2:如果上传后,出现文件下载框(一般为ie下),那么需要在服务端对response的header设置Content-Type: text/html。
1.25.4 实现基本上传功能
前端代码如下:
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#test1', //绑定元素
url: 'Test1', //上传接口
done: function (res) {
//上传完毕回调
alert("成功上传");
},
error: function () {
//请求异常回调
alert("上传失败");
}
});
script>
body>
html>
DTO类代码如下:
package dto;
public class UploadResponse {
private int code;
private String msg;
private Object data;
public UploadResponse() {
}
public UploadResponse(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
Servlet代码如下:
package controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import dto.UploadResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@WebServlet(name = "Test1", urlPatterns = "/Test1")
public class Test1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String uploadPath = "c:\\abc";
System.out.println(uploadPath);
SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
request.setCharacterEncoding("utf-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (int i = 0; i < items.size(); i++) {
FileItem fileItem = items.get(i);
if (fileItem.isFormField()) {
System.out.println(fileItem.getFieldName() + " "
+ new String(fileItem.getString().getBytes("iso-8859-1"), "utf-8"));
} else {
if (fileItem.getInputStream().available() != 0) {
Date nowDate = new Date();
String uploadFileName = format.format(nowDate);
uploadFileName = uploadFileName + "_" + System.currentTimeMillis() + "_" + Math.random() + "_"
+ fileItem.getName();
System.out.println(fileItem.getFieldName() + " " + fileItem.getName());
InputStream in = fileItem.getInputStream();
OutputStream out = new FileOutputStream(new File(uploadPath, uploadFileName));
byte b[] = new byte[1024];
int len = -1;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
out.close();
in.close();
}
}
}
UploadResponse uploadResponse = new UploadResponse();
String jsonString = new ObjectMapper().writeValueAsString(uploadResponse);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(jsonString);
out.flush();
out.close();
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行效果如图1-xx所示。
1.25.5 属性data和headers
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#test1', //绑定元素
url: 'Test2', //上传接口
data: { "username": "中国", "password": "中国人"},
headers: { "token": 'gaohongyan_token_token'},
done: function (res) {
//上传完毕回调
alert("成功上传");
},
error: function () {
//请求异常回调
alert("上传失败");
}
});
script>
body>
html>
Servlet代码如下:
package controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import dto.UploadResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@WebServlet(name = "Test2", urlPatterns = "/Test2")
public class Test2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
System.out.println(request.getHeader("token"));
String uploadPath = "c:\\abc";
System.out.println(uploadPath);
SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
request.setCharacterEncoding("utf-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (int i = 0; i < items.size(); i++) {
FileItem fileItem = items.get(i);
if (fileItem.isFormField()) {
System.out.println(fileItem.getFieldName() + " "
+ new String(fileItem.getString().getBytes("iso-8859-1"), "utf-8"));
} else {
if (fileItem.getInputStream().available() != 0) {
Date nowDate = new Date();
String uploadFileName = format.format(nowDate);
uploadFileName = uploadFileName + "_" + System.currentTimeMillis() + "_" + Math.random() + "_"
+ fileItem.getName();
System.out.println(fileItem.getFieldName() + " " + fileItem.getName());
InputStream in = fileItem.getInputStream();
OutputStream out = new FileOutputStream(new File(uploadPath, uploadFileName));
byte b[] = new byte[1024];
int len = -1;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
out.close();
in.close();
}
}
}
UploadResponse uploadResponse = new UploadResponse();
String jsonString = new ObjectMapper().writeValueAsString(uploadResponse);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(jsonString);
out.flush();
out.close();
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行效果如图1-xx所示。
1.25.6 属性accept
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>只能上传图片
button>
<button type="button" class="layui-btn" id="test2">
<i class="layui-icon">i>只能上传文件
button>
<button type="button" class="layui-btn" id="test3">
<i class="layui-icon">i>只能上传视频
button>
<button type="button" class="layui-btn" id="test4">
<i class="layui-icon">i>只能上传音频
button>
<script>
//accept可选值为:images(图片)、file(所有文件)、video(视频)、audio(音频)
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
url: 'AnyPath',
accept: 'images',
});
var uploadInst2 = upload.render({
elem: '#test2',
url: 'AnyPath',
accept: 'file',
});
var uploadInst3 = upload.render({
elem: '#test3',
url: 'AnyPath',
accept: "video"
});
var uploadInst4 = upload.render({
elem: '#test4',
url: 'AnyPath',
accept: "audio"
});
script>
body>
html>
上传的文件类型没有通过校验,如图1-xx所示。
1.25.7 属性exts
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>只能上传png图片
button>
<script>
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
url: 'AnyPath',
accept: 'images',
exts: 'png'
});
script>
body>
html>
上传非png格式出现异常,如图1-xx所示。
也支持多个扩展名:
exts: 'zip|rar|pdf|jpg|doc|docx|xls|xlsx'
1.25.8 属性acceptMime
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
url: 'AnyPath',
acceptMime: "image/jpeg,image/png"//只能上传jpeg或png格式
});
script>
body>
html>
Chrome浏览器运行效果如图1-xx所示。
可以过滤文件类型,只显示jpeg或png格式的文件。
1.25.9 属性auto和bindAction
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<button type="button" class="layui-btn" id="beginUpload">
开始上传
button>
<script>
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
url: 'AnyPath',
auto: false,
bindAction: "#beginUpload"
});
script>
body>
html>
1.25.10 结合其它表单处理上传
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<div class="layui-form-item">
<label class="layui-form-label">输入框label>
<div class="layui-input-block">
<input type="text" id="username" placeholder="请输入账号" autocomplete="off" class="layui-input">
div>
div>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<button type="button" class="layui-btn" id="beginUpload">
开始上传
button>
<script>
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
auto: false,
});
$(document).ready(function () {
$("#beginUpload").click(function () {
var usernameValue = $("#username").val();
var inputFile = $("input[type=file]")[0].files[0];
var formData = new FormData();
formData.append('username', usernameValue)
formData.append('uploadFile', inputFile);
$.ajax({
url: 'Test1?t=' + new Date().getTime(),
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function () {
alert("上传成功!");
}
});
});
});
script>
body>
html>
运行效果如图1-xx所示。
此案例是ajax无刷新版上传,使用
并更改相应的代码可以实现有刷新上传。1.25.11 属性field
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
//accept可选值为:images(图片)、file(所有文件)、video(视频)、audio(音频)
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
url: 'Test1',
field: "zzzzzzzzzzzzzzzz"
});
script>
body>
html>
运行结果如图1-xx所示。
1.25.12 属性size
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
url: 'Test1',
size: 20
});
script>
body>
html>
运行结果如图1-xx所示。
1.25.13 属性multiple
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
url: 'Test1',
auto: false,
multiple: true
});
script>
body>
html>
运行效果如图1-xx所示。
同时上传5个文件。
1.25.14 属性number
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
url: 'Test1',
auto: false,
multiple: true,
number: 2
});
script>
body>
html>
运行效果如图1-xx所示。
1.25.15 属性drag
upload组件默认支持拖拽,本案例进行了禁用。
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
url: 'Test1',
multiple: true,
drag: false
});
script>
body>
html>
当把图片拖拽到上传组件时,并不是上传,而是在浏览器中打开图片,因为拖拽被禁用了。
1.25.16 回调choose
在文件被选择后触发,该回调会在before回调之前执行。一般用于非自动上传(即auto:false)的场景,比如预览图片等。
示例代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
auto: false,
multiple: true,
choose: function (obj) {
//将每次选择的文件追加到文件队列
var files = obj.pushFile();
//预读本地文件,如果是多文件,则会遍历。(不支持ie8/9)
obj.preview(function (index, file, result) {
console.log(index); //得到文件索引
console.log(file); //得到文件对象
console.log(result); //得到文件base64编码,比如图片
//obj.resetFile(index, file, '123.jpg'); //重命名文件名
//这里还可以做一些append文件列表DOM的操作
//obj.upload(index, file); //对上传失败的单个文件重新上传,一般在某个事件中使用
//delete files[index]; //删除列表中对应的文件,一般在某个事件中使用
});
}
});
script>
body>
html>
事实上这是一个非常实用的功能,可轻松应对复杂的列表文件上传管理,示例代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<div class="layui-upload">
<button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件button>
<div class="layui-upload-list">
<table class="layui-table">
<thead>
<th>文件名th>
<th>大小th>
<th>状态th>
<th>操作th>
thead>
<tbody id="demoList">tbody>
table>
div>
<button type="button" class="layui-btn" id="testListAction">开始上传button>
div>
<script>
//多文件列表示例
var demoListView = $('#demoList');
var upload = layui.upload;
var uploadListIns = upload.render({
elem: '#testList',
url: 'Test1',
accept: 'file',
multiple: true,
auto: false,
bindAction: '#testListAction',
choose: function (obj) {
var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
//读取本地文件
obj.preview(function (index, file, result) {
var tr = $(['+ index + '">' '].join(''));
, '' + file.name + ' '
, '' + (file.size / 1024).toFixed(1) + 'kb '
, '等待上传 '
, '' '
, '重传'
, '删除'
, '
, '
//单个重传
tr.find('.demo-reload').on('click', function () {
obj.upload(index, file);
});
//删除
tr.find('.demo-delete').on('click', function () {
delete files[index]; //删除对应的文件
tr.remove();
uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
});
demoListView.append(tr);
});
},
done: function (res, index, upload) {
if (res.code == 0) { //上传成功
var tr = demoListView.find('tr#upload-' + index)
, tds = tr.children();
tds.eq(2).html('上传成功');
tds.eq(3).html(''); //清空操作
return delete this.files[index]; //删除文件队列已经上传成功的文件
}
this.error(index, upload);
},
error: function (index, upload) {
var tr = demoListView.find('tr#upload-' + index)
, tds = tr.children();
tds.eq(2).html('上传失败');
tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
}
});
script>
body>
html>
1.25.17 回调before
在choose回调之后、done/error回调之前触发。返回的参数完全类似choose回调。一般用于上传完毕前的loading、图片预览等。
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#test1', //绑定元素
url: 'Test1', //上传接口
before: function (obj) { //obj参数包含的信息,跟 choose回调完全一致,可参见上文。
layer.load(); //上传loading
},
done: function (res, index, upload) {
layer.closeAll('loading'); //关闭loading
},
error: function (index, upload) {
layer.closeAll('loading'); //关闭loading
}
});
script>
body>
html>
1.25.18 回调done
在上传接口请求完毕后触发,但文件不一定是上传成功的,只是接口的响应状态正常(200)。回调返回三个参数,分别为:服务端响应信息、当前文件的索引、重新上传的方法。
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#test1', //绑定元素
url: 'Test1', //上传接口
multiple: true,
before: function (obj) { //obj参数包含的信息,跟 choose回调完全一致,可参见上文。
layer.load(); //上传loading
},
done: function (res, index, upload) {
alert('done run !');
//假设code=0代表上传成功
if (res.code == 0) {
//do something (比如将res返回的图片链接保存到表单的隐藏域)
}
//获取当前触发上传的元素,一般用于 elem 绑定 class 的情况,注意:此乃 layui 2.1.0 新增
var item = this.item;
//文件保存失败
//do something
var test = "123";
}
});
script>
body>
html>
1.25.19 回调error
当请求上传时出现异常时触发(如网络异常、404/500等)。回调返回两个参数,分别为:当前文件的索引、重新上传的方法。
前端代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<div id="demoText">div>
<script>
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#test1', //绑定元素
url: 'TestXXXXXXXXXXXXX', //错误的上传路径
multiple: true,
error: function (index, upload) {
//当上传失败时,可以生成一个“重新上传”的按钮,点击该按钮时,执行upload()方法即可实现重新上传。
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText.html('上传失败 重试');
demoText.find('.demo-reload').on('click', function () {
uploadInst.upload();
});
}
});
script>
body>
html>
如下写法效果一样:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<div id="demoText">div>
<script>
var upload = layui.upload;
//执行实例
upload.render({
elem: '#test1', //绑定元素
url: 'TestXXXXXXXXXXXXX', //错误的上传路径
multiple: true,
error: function (index, upload) {
//当上传失败时,可以生成一个“重新上传”的按钮,点击该按钮时,执行upload()方法即可实现重新上传。
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText.html('上传失败 重试');
demoText.find('.demo-reload').on('click', function () {
upload();
});
}
});
script>
body>
html>
1.25.20 多文件上传完毕后的状态回调
只有当开启多文件时(即multiple: true),该回调才会被触发。回调返回一个object类型的参数,包含一些状态数据。
示例代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<script>
var upload = layui.upload;
var uploadInst1 = upload.render({
elem: '#test1',
url: 'Test1',
multiple: true,
allDone: function (obj) { //当文件全部被提交后,才触发
console.log(obj.total); //得到总文件数
console.log(obj.successful); //请求成功的文件数
console.log(obj.aborted); //请求失败的文件数
},
done: function (res, index, upload) {
//每个文件提交一次触发一次
console.log("done " + index);
}
});
script>
body>
html>
执行效果如图1-xx所示。
1.25.21 文件上传进度的回调
在网速一般的情况下,大文件的上传通常需要一定时间的等待,而浏览器并不会醒目地告知它正在努力地上传中,此时为了提升用户体验,可以通过该回调制作一个进度条。
示例代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<div class="layui-progress" lay-filter="demo">
<div class="layui-progress-bar">div>
div>
<script>
var upload = layui.upload;
var element = layui.element;
upload.render({
elem: '#test1',
url: 'Test1',
multiple: true,
progress: function (n, elem) {
var percent = n + '%' //获取进度百分比
element.progress('demo', percent); //可配合layui进度条元素使用
console.log(elem); //得到当前触发的元素DOM对象。可通过该元素定义的属性值匹配到对应的进度条。
}
});
script>
body>
html>
1.25.22 重载实例
有时可能需要对upload.render()进行重载,通过改变一些参数(如将上传文件重置为只上传图片等场景)来重置功能,示例代码如图1-xx所示。
测试代码如下:
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="js/jquery3.5.1.js">script>
<link rel="stylesheet" href="layui/css/layui.css"/>
<script src="layui/layui.all.js">script>
head>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon">i>上传图片
button>
<input type="button" id="uploadJPEG" value="只能上传jpeg文件"/>
<script>
var upload = layui.upload;
var element = layui.element;
var myupload = upload.render({
elem: '#test1',
url: 'Test1',
multiple: true,
accept: 'images',
exts: 'png',
progress: function (n, elem) {
var percent = n + '%' //获取进度百分比
element.progress('demo', percent); //可配合layui进度条元素使用
console.log(elem); //得到当前触发的元素 DOM 对象。可通过该元素定义的属性值匹配到对应的进度条。
}
});
$(document).ready(function () {
$("#uploadJPEG").click(function () {
myupload.reload({
multiple: true,
accept: 'images',
exts: 'jpg|jpeg'
});
});
});
script>
body>
html>
点击button后,upload组件由原来的只能上传png改成只能上传jpg文件。
1.25.23 重新上传
在执行upload.render(options)方法时,其实有返回一个实例对象,以便实现重新上传等操作。注意:这是对当前上传队列的全局重新上传,而choose回调返回的obj.upload(index, file)方法则是对单个文件进行重新上传,示例代码如图1-xx所示。
手动重新上传的案例前面章节已经进行了介绍。