传统的上传文件方式是首先将文件上传到指定路径,然后再从该路径下解析文件内容;这种方式实现比较繁琐,并且暴漏了文件上传的路径,造成了安全隐患。现在我们介绍的是另一种方式,直接读取文件流的方式,这种方式更加简单安全,而且不占用服务器内存。
一. jsp页面
1. list.jsp
<ul>
<li><a class="icon" title="导入文件" rel="dlg_import_comment" target="dialog"
width="600" height="300" href="${ctx}/admin/comment/import.jsp"><span>导入文件</span></a></li>
<li><a class="icon" title="下载文件模版" href="${ctx}/admin/comment/comment_template.xls"><span>下载文件Excel模版</span></a></li>
<li>line</li>
</ul>
2. import.jsp
<%@ page contentType="text/html; charset=UTF-8" session="false" %>
<%@ include file="/WEB-INF/jspf/import.jspf" %>
<div class="pageContent">
<form method="post" action="${ctx}/admin/comment/import.do" enctype="multipart/form-data"
class="pageForm" οnsubmit="return iframeCallback(this, dialogAjaxDone);">
<div class="pageFormContent" layoutH="56">
<fieldset>
<legend>请选择Excel文件,请务必按照规定的模版录入数据</legend>
<dl class="nowrap">
<dd><input class="required" type="file" name="file"/></dd>
</dl>
</fieldset>
</div>
<div class="formBar">
<ul>
<li><div class="buttonActive"><div class="buttonContent"><button type="submit">导入</button></div></div></li>
<li><div class="button"><div class="buttonContent"><button class="close" type="button">关闭</button></div></div></li>
</ul>
</div>
</form>
</div>
二. controller控制层
commentController.java
@RequestMapping(value = "/comment/import.do", method = RequestMethod.POST)
public String doImport(HttpServletRequest req, HttpServletResponse resp) throws Exception {
// 权限验证
if (!AuthFacade.hasRight(AUTHFUNCTIONID_ALL, true, resp)) {
return null;
}
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
if (!isMultipart) {
showMessage(req, resp, 300, "没有选择文件,请重新上传", null, null);
}
// 计数器
int count = 0;
int fail = 0;
StringBuffer failBuf = new StringBuffer();// 记录必填项为空的
StringBuffer notExistsBuf = new StringBuffer(); // 记录不存在的
StringBuffer lengthBuf = new StringBuffer(); // 记录超出长度的
StringBuffer ruleBuf = new StringBuffer(); // 记录格式不正确的
Integer statusCode = 200;
String msg = "";
Cell cell = null;
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置上传文件大小的上限10m,-1表示无上限
upload.setFileSizeMax(1024 * 1024 * 10);
upload.setHeaderEncoding("gbk");
// 得到所有表单字段对象的集合
List<FileItem> fileItems = null;
try {
fileItems = upload.parseRequest(req);
} catch (FileUploadException e) {
e.printStackTrace();
showMessage(req, resp, 300, "解析上传的文件出错,请稍后重试", false, false);
}
if (fileItems == null || fileItems.isEmpty()) {
showMessage(req, resp, 300, "文件为空,请重新上传", false, false);
}
// 迭代导入到表内数据
Iterator it = fileItems.iterator();
while (it.hasNext()) {
FileItem fi = (FileItem) it.next();
if (!fi.isFormField()) {
InputStream is = fi.getInputStream();
Workbook wb = null;
try {
wb = Workbook.getWorkbook(is);
} catch (Exception e) {
e.printStackTrace();
resp.setCharacterEncoding("UTF-8");
resp.getWriter().println(new JSONBuilder().put("statusCode", 300).put("message", "读取Excel表格出错,请检查Excel表格, 或者稍后重试").toString());
return null;
}
// 读取第一个工作本
Sheet sheet = wb.getSheet(0);
if (sheet != null) {
int rowNum = sheet.getRows();
// 聚合词
Comment comment = null;
CommentImg commentImg = null;
int groupId = 0; // 团购ID
int goodsId = 0; // 商品ID
int userId = 0; // 马甲ID
Date createAt = null; // 评论时间
String content = ""; // 评论
String url1 = ""; // 图片URL1
String url2 = ""; // 图片URL2
String url3 = ""; // 图片URL3
String url4 = ""; // 图片URL4
String url5 = ""; // 图片URL5
String uId = "";
String goId = "";
String grId = "";
String date = "";
long commentId = 0;
// 从第二行开始拿数据
for (int i = 1; i < rowNum; i++) {
List<String> str = new ArrayList<String>();
Cell[] cells = sheet.getRow(i);
if (cells != null && cells.length > 0) {
// A.团购ID
if (0 < cells.length) {
cell = cells[0];
} else {
cell = null;
}
if (cell != null) {
grId = Utils.toInput(cell.getContents());
if (Utils.isBlank(grId)) {
fail++;
failBuf.append((i + 1) + ";");
continue;
}
groupId = Utils.intValue(grId, -1);
if (groupId <= 0 || null == groupService.findGroup(groupId)) {
fail++;
notExistsBuf.append((i + 1) + ";");
continue;
}
} else {
fail++;
failBuf.append((i + 1) + ";");
continue;
}
// B.商品ID
if (1 < cells.length) {
cell = cells[1];
} else {
cell = null;
}
if (cell != null) {
goId = Utils.toInput(cell.getContents());
if (Utils.isBlank(goId)) {
fail++;
failBuf.append((i + 1) + ";");
continue;
}
goodsId = Utils.intValue(goId, -1);
if (goodsId <= 0 || null == goodsService.findGoods(goodsId)) {
fail++;
notExistsBuf.append((i + 1) + ";");
continue;
}
} else {
fail++;
failBuf.append((i + 1) + ";");
continue;
}
// C.马甲ID
if (2 < cells.length) {
cell = cells[2];
} else {
cell = null;
}
if (cell != null) {
uId = Utils.toInput(cell.getContents());
if (Utils.isBlank(uId)) {
fail++;
failBuf.append((i + 1) + ";");
continue;
}
userId = Utils.intValue(uId, -1);
Account account = userService.findAccount(userId);
if (account == null) {
fail++;
notExistsBuf.append((i + 1) + ";");
continue;
}
} else {
fail++;
failBuf.append((i + 1) + ";");
continue;
}
// D.评论时间
if (3 < cells.length) {
cell = cells[3];
} else {
cell = null;
}
if (cell != null) {
date = Utils.toInput(cell.getContents());
if (Utils.isBlank(date)) {
fail++;
failBuf.append((i + 1) + ";");
continue;
}
date = date.replace("/", "-");
boolean isDate = Utils.isValidDate(date);
if (isDate == true) {
createAt = Utils.parseToDate(date, "yyyy-MM-dd HH:mm:ss");
}
if (createAt == null) {
fail++;
ruleBuf.append((i + 1) + ";");
continue;
}
} else {
fail++;
failBuf.append((i + 1) + ";");
continue;
}
// E.评论
if (4 < cells.length) {
cell = cells[4];
} else {
cell = null;
}
if (cell != null) {
content = Utils.toInput(cell.getContents());
if (Utils.isBlank(content)) {
fail++;
failBuf.append((i + 1) + ";");
continue;
}
if (content.length() > 1000) {
fail++;
lengthBuf.append((i + 1) + ";");
continue;
}
} else {
fail++;
failBuf.append((i + 1) + ";");
continue;
}
// F.图片URL1
if (5 < cells.length) {
cell = cells[5];
} else {
cell = null;
}
if (cell != null) {
url1 = Utils.toInput(cell.getContents());
if (!Utils.isBlank(url1)) {
if (url1.length() > 255) {
fail++;
lengthBuf.append((i + 1) + ";");
continue;
}
str.add(url1);
}
}
// G.图片URL2
if (6 < cells.length) {
cell = cells[6];
} else {
cell = null;
}
if (cell != null) {
url2 = Utils.toInput(cell.getContents());
if (!Utils.isBlank(url2)) {
if (url2.length() > 255) {
fail++;
lengthBuf.append((i + 1) + ";");
continue;
}
str.add(url2);
}
}
// H.图片URL3
if (7 < cells.length) {
cell = cells[7];
} else {
cell = null;
}
if (cell != null) {
url3 = Utils.toInput(cell.getContents());
if (!Utils.isBlank(url3)) {
if (url3.length() > 255) {
fail++;
lengthBuf.append((i + 1) + ";");
continue;
}
str.add(url3);
}
}
// I.图片URL4
if (8 < cells.length) {
cell = cells[8];
} else {
cell = null;
}
if (cell != null) {
url4 = Utils.toInput(cell.getContents());
if (!Utils.isBlank(url4)) {
if (url4.length() > 255) {
fail++;
lengthBuf.append((i + 1) + ";");
continue;
}
str.add(url4);
}
}
// J.图片URL5
if (9 < cells.length) {
cell = cells[9];
} else {
cell = null;
}
if (cell != null) {
url5 = Utils.toInput(cell.getContents());
if (!Utils.isBlank(url5)) {
if (url5.length() > 255) {
fail++;
lengthBuf.append((i + 1) + ";");
continue;
}
str.add(url5);
}
}
int hasImg = 0;
if (null != str && str.size() > 0) {
hasImg = 1;
}
comment = new Comment();
comment.setGroupId(groupId);
comment.setGoodsId(goodsId);
comment.setUserId(userId);
comment.setStatus(Comment.STATUS_NORMAL);
comment.setContent(content);
comment.setCreateAt(createAt);
comment.setHasImg(hasImg);
commentId = commentService.createComment(comment);
for (String url : str) {
commentImg = new CommentImg();
commentImg.setCommentId(commentId);
commentImg.setImgUrl(url);
commentImg.setCreateBy(userId);
commentService.createCommentImg(commentImg);
}
count++;
}
}
}
}
}
resp.setCharacterEncoding("UTF-8");
msg = "成功导入" + count + "条评论,失败" + ((0 > fail) ? 0 : fail) + "条! ";
if (fail > 0) {
statusCode = 300;
msg += "原因:";
if (!Utils.isBlank(failBuf.toString())) {
msg += "必填项是否为空;行号为:" + failBuf.toString() + ";";
}
if (!Utils.isBlank(notExistsBuf.toString())) {
msg += "团购ID或商品ID或马甲ID不存在;行号为:" + notExistsBuf.toString() + ";";
}
if (!Utils.isBlank(lengthBuf.toString())) {
msg += "评论内容或图片url长度太长;行号为:" + lengthBuf.toString() + ";";
}
if (!Utils.isBlank(ruleBuf.toString())) {
msg += "评论时间格式不对;行号为:" + ruleBuf.toString() + ";";
}
}
if (fail == 0) {
showMessage(req, resp, statusCode, msg, true, true);
} else {
showMessage(req, resp, statusCode, msg, false, false);
}
return null;
}
注意:传统文件上传方式需要在.xml文件配置文件上传监听multipartResolver,每次文件上传都会被监听到并先进行一次内容解析,再将解析后的内容传到controller层进行处理,而新方式是直接在controller层进行解析再处理,所以无需配置监听,若配置了监听二次解析是获取不到文件内容的。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2000000"/>
</bean>