要说逻辑其实也不难,新建一个form表单,表单有action处理页面,action页面就是处理上传的页面,这个dropzone插件的任务就是帮你对上传的文件进行列队上传,就像管理员:你们这群孩子,领奖状就要排好队,一次上n个(默认是2个,可配置)来领奖,后面的同学排好队,等待领奖。并且监听每一个文件的上传状态。接下来上代码:

index.jsp(注意,此form需要添加class="dropzone",因为这个是dropzone.css给dropzone类定义的样式)

官方文档(英文版):https://www.dropzonejs.com/#event-sending

官方文档(中文版):http://wxb.github.io/dropzonejs.com.zh-CN/dropzonezh-CN/#installation

<%@ 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>dropzone上传插件测试</title>

<!-- jquery -->
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-3.3.1.min.js"></script>

<!-- 注意:引入dropzone的js和css文件最好放在同一个目录,不然的话,会出现各种错误 -->
<script type="text/javascript" src="${pageContext.request.contextPath }/static/dropzone/dropzone.js"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/dropzone/dropzone.css" >

<style type="text/css">
#uploadForm {
min-height: 200px;
width: 800px;
margin-right: -810px;
margin-bottom: 30px;
display: inline-block;
background-color:white;
}
#uploadForm #uploadBtn {
position: absolute;
top: 2px;
right: -294px;
font-family: "方正舒体";
font-size: 40px;
width: 276px;
height: 80px;
cursor: pointer;
}
</style>

<script type="text/javascript">
/* Dropzone上传插件配置 */

var IsServerError = false;//服务器获取配置出错
var fileList = new Array();
var fileList_Uploading = new Array();
var uploaded_filePaths = new Array();//已上传的文件在服务器的路径集合;用于遇到异常时删除已上传的文件。(相当于回滚)
var arr_file = new Array();
var arr_xhr = new Array();
Dropzone.options.uploadForm = { //此处的"uploadForm" 是dropzone的HTML元素ID的驼峰命名,比如<form > 确 认 上 传 </button> -->
</form>




</body>
</html>

上面的代码是图一效果图。

然后激活dropzone的脚本也有了,配置也有注释了,我就挑几个再讲讲吧

addRemoveLinks:true//每个文件添加“删除”链接

acceptedFiles:定义的是可接受文件类型,也就是在选择文件时帮你筛选以上类型的文件出来给你选。

parallelUploads:最大并行处理量,也就是上面提到的,一次上来n个孩子上台领奖,这个n是多少,就是在此处配置。

autoProcessQueue:默认是true,为true代表文件拖放到上传域或选择文件之后马上帮你上传,相当于自动上传。如果设置为false的话,那选择文件后不会进行上传,只是单纯的把文件列出来,当点击“上传”按钮才会触发上传,这个按钮需要绑定click事件来触发上传,也就是我上面的init函数注释掉的,那个就是用来进行手动触发上传的。但手动触发上传存在一个大大的问题,就是点击一次帮你上传parallelUploads个文件,后面排队的文件不会继续上传,需要再点击一次上传,那排队中的下两个才会触发上传,因此,要么你设置该参数为true(自动上传),要么你设置为false(手动上传)并且将parallelUploads设置得大一点(如:100)。这样,上传者才会好受一点。个人觉得还是用自动上传最好。

previewTemplate:每一个文件的html模板,如上图图二,不管上传成功 / 上传中 / 等待上传的文件都使用这个html模板进行拼接。注意:是以这个html作为模板进行拼接,显示。

事件:

addedfile:每拖放/选择一个文件进来都会执行一次该函数

canceled:取消上传该文件。取消后会自动调用removedfile事件

uploadprogress:文件上传中的处理,dropzone原本已经做好了进度条控制,你要自定义进度条的话,在这里进行自定义配置

success:每一个文件上传成功都会触发该函数。

queuecomplete:当所有文件处理完成执行该函数

removedfile:移除该文件(注意:dropzone仅将前端的UI删除,并不会真正删除你服务器上面的文件,因此,需要在该函数添加一个ajax事件进行删除服务器上的该文件。删除文件,那就需要文件所在路径,那,我怎么知道这个文件的路径?哈哈,所以我在html模板添加了一个div用来存放这个服务器文件的路径,我说了,每上传成功一个文件就会触发一次success事件,我们就在这个事件里面将上传成功的文件路径放到html模板中,然后系统会自动拼接这个html模板到上传域中,你说,我是不是很聪明。哈哈)

error:文件不在可接受文件类型范围内 / 上传失败 时触发该函数。


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import upload.model.UploadResult;


public class Upload {

public static String basePath = "D:/WebSite/KMS";
public static String baseFoder = "Test";


/*
* @version 1.0
* @author Demonor
* @Class IsUsing = true
* */



public static void multi_upload(String UID,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{

boolean error = false;
String physical_path = "";
String server_path = "";
UploadResult result = new UploadResult();
List<UploadResult> list_client = new ArrayList<UploadResult>();
List<UploadResult> list_server = new ArrayList<UploadResult>();


Gson gson = new Gson();
JSONObject json = new JSONObject();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
SimpleDateFormat fmt = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");
String date = fmt.format(System.currentTimeMillis());
error = (baseFoder.equals(""))?true:false;
String upload_foder = basePath+"/"+baseFoder;
error = (upload_foder.equals(""))?true:false;
System.out.println("error:"+error);
if(!error) {
upload.setHeaderEncoding("UTF-8");
try{
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("utf-8");
} else {
String fieldName = item.getFieldName();
String OriginalName = item.getName().substring(item.getName().lastIndexOf("\\")+1);
String fileName = OriginalName.substring(0, OriginalName.lastIndexOf("."))+"¤※◎"+String.valueOf(UID)+"_"+date+"¤※◎"+item.getName().substring(item.getName().lastIndexOf("."),item.getName().length());;
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
File f = new File(upload_foder);
if(!f.exists()) {
f.mkdirs();
}
server_path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/temp/"+fileName;
physical_path = upload_foder+"/"+fileName;
File uploadedFile = new File(physical_path);

System.out.println("physical_path:"+physical_path);
//System.out.println("fileName:"+fileName);
//System.out.println(uploadedFile.length()+"============");
item.write(uploadedFile);
list_server.add(new UploadResult(fileName,uploadedFile.length(),physical_path,""));
list_client.add(new UploadResult(OriginalName,uploadedFile.length(),physical_path,""));

}
} /* while */
}catch(Exception e){
e.printStackTrace();
}
}


response.setContentType("text/text;charset=utf-8");
PrintWriter out = response.getWriter();
json.put("error", error);
json.put("list_server", gson.toJson(list_server));
json.put("list_client", gson.toJson(list_client));
out.print(json.toString()); //
out.flush();
out.close();


}

public static int removeFile(String[] paths,HttpSession session) {
int k = 0;
for(String filePath : paths) {
boolean b = false;
filePath = ScriptDecoder.unescape(ScriptDecoder.unescape(filePath));
File file = new File(filePath);
if (!file.exists()) {
System.out.println("系统找不到指定的路径:" + filePath);
}else{
b = file.delete();
k ++;
}
}
return k;
}

}

model:


import java.io.Serializable;

public class UploadResult implements Serializable{

/**
*
*/
private static final long serialVersionUID = 7434128027715196787L;
private String fileName; //文件名称
private long fileSize; //文件大小
private String physical_path;//文件上传到服务器的物理路径
private String server_path; //文件上传到服务器的服务器路径,可访问的http://xxx.com/xxx.png


public UploadResult() {}
public UploadResult(String fileName,long fileSize,String physical_path,String server_path) {
this.fileName = fileName;
this.fileSize = fileSize;
this.physical_path = physical_path;
this.server_path = server_path;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}

public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getPhysical_path() {
return physical_path;
}
public void setPhysical_path(String physical_path) {
this.physical_path = physical_path;
}
public String getServer_path() {
return server_path;
}
public void setServer_path(String server_path) {
this.server_path = server_path;
}
public static long getSerialversionuid() {
return serialVersionUID;
}


}


————————————————
版权声明:本文为CSDN博主「Demonor_」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/A13432421434/article/details/87860661

相关文章: