web端使用plupload上传文件,支持文件多选,显示文件大小、上传进度。
java服务器servlet保存客户端上传的文件,使用commons-fileupload-1.3.2组件
HTML、JS代码
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Update Config Files</title>
<script type="text/javascript" src="scripts/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="scripts/plupload-2.1.3/moxie.min.js"></script>
<script type="text/javascript"
src="scripts/plupload-2.1.3/plupload.min.js"></script>
<script type="text/javascript" src="scripts/utils/util-find-parent.js"></script>
</head>
<body style="font: 13px Verdana; background: #eee; color: #333">
<h1>上传(更新)配置文件</h1>
<div id="filelist">Your browser doesn‘t have Flash, Silverlight
or HTML5 support.</div>
<br />
<div id="container">
<button type="button" id="pickfiles">选择文件</button>
<button type="button" id="uploadfiles">开始上传</button>
</div>
<br />
<div id="console"></div>
<script type="text/javascript">
//保存等待上传的文件
var preUploadFiles = new Array();
var fileError = false;
/**
* 点击“删除”按钮删除对应的文件项
* @param {type} obj button对象
* @returns {undefined}
*/
function removeFileByButton1(obj) {
var p = findParent(obj, ".upFileItemDiv");
if (p == null) {
return;
}
pid = p.id;
p.parentNode.removeChild(p);
var index = -1;
for (var i = 0; i < preUploadFiles.length; i++) {
var file = preUploadFiles[i];
if (file.id == pid) {
file.destroy();
uploader.removeFile(file);
index = i;
break;
}
}
if (index >= 0) {
preUploadFiles.splice(index, 1);
}
}
var clearPreUploadFiles = function() {
for (var i = 0; i < preUploadFiles.length; i++) {
var file = preUploadFiles[i];
file.destroy();
uploader.removeFile(file);
}
preUploadFiles.length = 0;
};
var uploader = new plupload.Uploader({
runtimes : ‘html5,flash,silverlight,html4‘,
browse_button : ‘pickfiles‘,
container : document.getElementById(‘container‘),
url : ‘UploadServlet?‘ + Math.random(),
flash_swf_url : ‘scripts/plupload-2.1.3/Moxie.swf‘,
silverlight_xap_url : ‘scripts/plupload-2.1.3/Moxie.xap‘,
filters : {
max_file_size : ‘4mb‘,
mime_types : [ {
title : "Txt files",
extensions : "txt"
}, {
title : "Properties files",
extensions : "properties"
}, {
title : "Excel 2003",
extensions : "xls"
}, {
title : "Excel 2007 or above",
extensions : "xlsx"
}, {
title : "Excel XLSM",
extensions : "xlsm"
} ],
prevent_duplicates : true//不允许选取重复文件
},
init : {
PostInit : function() {
document.getElementById(‘filelist‘).innerHTML = ‘‘;
document.getElementById(‘pickfiles‘).onclick = function() {
clearPreUploadFiles();
fileError = false;
document.getElementById(‘filelist‘).innerHTML = ‘‘;
document.getElementById(‘console‘).innerHTML = ‘‘;
};
document.getElementById(‘uploadfiles‘).onclick = function() {
if (uploader.files.length == 0) {
alert("请先选择上传的文件");
returnfalse;
}
for (var i = 0; i < preUploadFiles.length; i++) {
var file = preUploadFiles[i];
var btn = document.getElementById(file.id + "_btn");
if (btn != null && btn != undefined) {
btn.parentNode.removeChild(btn);
}
}
uploader.start();
returnfalse;
};
},
FilesRemoved : function(up, files) {
//plupload.each(files, function(file) {//});
},
FilesAdded : function(up, files) {
plupload.each(files, function(file) {
preUploadFiles.push(file);
var str = "<button type=‘button‘ id=‘" + (file.id + "_btn") + "‘ onclick=‘removeFileByButton1(this);‘>删除</button>";
document.getElementById(‘filelist‘).innerHTML += ‘<div class=\‘upFileItemDiv\‘ id="‘ + file.id + ‘">‘ + file.name + ‘ (‘ + plupload.formatSize(file.size) + ‘) <b></b>‘ + str + ‘</div>‘;
});
},
FileUploaded : function(up, file, responseObject) {
var responseInfo = responseObject.response;
if (responseObject != null && responseInfo != null) {
if (responseInfo.indexOf("success") != 0) {
fileError = true;
}
document.getElementById(‘console‘).innerHTML += "\nInfo #" + file.name + " : " + responseObject.response + "</br>";
}
},
UploadProgress : function(up, file) {
document.getElementById(file.id).getElementsByTagName(‘b‘)[0].innerHTML = ‘<span>‘ + file.percent + "%</span>";
},
UploadComplete : function(up, files) {
document.getElementById(‘filelist‘).innerHTML = "";
clearPreUploadFiles();
},
Error : function(up, err) {
//alert(Error #" + err.code + ": " + err.message);document.getElementById(‘console‘).innerHTML += "\nError #" + err.code + ": " + err.message + "</br>";
}
}
});
uploader.init();
</script>
</body>
</html>
补充一个util-find-parent.js文件
/**
* 向上寻找父对象
* @param {HTMLElement} element
* @param {String} param 包含.表示寻找class的父级,包含#表示寻找id的父级
* @param {Number} depth 向上查询父级的层级(深度)
* @returns {element.parentNode}
*/
function findParent(element, param, depth) {
var ps = param.split(" ");
var pobjs = new Array();
for (var n = 0; n < ps.length; n++) {
var str = ps[n];
var index = str.indexOf(".");
if (index >= 0) {
pobjs.push({type: 1, name: str.substr(1, str.length - 1)});
} else {
index = str.indexOf("#");
if (index >= 0) {
pobjs.push({type: 2, name: str.substr(1, str.length - 1)});
} else {
pobjs.push({type: 3, name: str});
}
}
}
if (pobjs.length == 0)
return null;
var max = (depth == undefined || depth <= 0) ? 10 : depth;
var i = 0;
while (i < max) {
if (element == null || element == undefined) {
break;
}
for (var j = 0; j < pobjs.length; j++) {
var obj = pobjs[j];
if (obj.type == 1) {
if (element.className == obj.name) {
return element;
}
} else if (obj.type == 2) {
if (element.id == obj.name) {
return element;
}
} else if (obj.type == 3) {
if (element.name == obj.name) {
return element;
}
}
}
element = element.parentNode;
i++;
}
return null;
}
下面是java服务器接收客户端上传的文件数据并保存
import ch.qos.logback.classic.Logger;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
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 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 org.slf4j.LoggerFactory;
/**
*
* @author zkpursuit
*/
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
public class UploadServlet extends HttpServlet {
private final Logger logger = (Logger) LoggerFactory.getLogger(UploadServlet.class);
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
// 设置缓冲区大小,这里是4kb
factory.setSizeThreshold(4096);
// 设置缓冲区目录
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 设置最大文件尺寸,这里是4MB
upload.setSizeMax(4194304);
String error = null;
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField()) {
String uploadPath = request.getServletContext().getRealPath("/usr.config");
File fold = new File(uploadPath);
if (!fold.exists()) {
fold.mkdir();
}
String fileName = item.getName();
try {
File targetFile = new File(uploadPath + "/" + fileName);
if (!targetFile.exists()) {
targetFile.createNewFile();
}
item.write(targetFile);
} catch (Exception ex) {
error = ex.getMessage();
if (error == null) {
error = ex.toString();
}
logger.error(error, ex);
}
}
}
} catch (FileUploadException ex) {
error = ex.getMessage();
if (error == null) {
error = ex.toString();
}
logger.error(error, ex);
}
try (PrintWriter pw = response.getWriter()) {
if (error != null) {
pw.append("faild -> <b style=\"color:#FF0000;\">(严重)" + error + "</b>");
} else {
pw.append("success -> 上传完成!");
}
pw.flush();
}
}
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
转自:https://my.oschina.net/zkpursuit/blog/798916
时间: 2024-11-08 04:31:44