搭建环境
这里使用maven导入jar包:
<dependencies>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!--json-->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
</dependencies>
三个主要的jar包,这里还将使用jquery以及异步提交表单,所以需要jquery和jquery.form文件
jsp页面
<%--
Created by IntelliJ IDEA.
User: wqh
Date: 2017/5/26
Time: 9:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.form.js"></script>
<script type="text/javascript">
$(function () {
$("#sub").bind("click",function () {
var option = {
type:"post",
url:"${pageContext.request.contextPath}/TestServlet",
async: true,
enctype:"multipart/form-data",
dataType:"json",
error:function(data){
alert(data);
},
success:function(msg){
//将结果格式化为json
var json = eval(msg);
var data = "";
$.each(json,function (index,item) {
var key = json[index].file;
data = data +"==="+ key
});
alert(data);
}
};
$("#fileForm").ajaxSubmit(option);
})
});
</script>
<head>
<title>Title</title>
</head>
<body>
<form action="#" id="fileForm" enctype="multipart/form-data" method="post" >
<input type="file" name="file"/><br>
<input type="file" name="file"/><br>
<input type="file" name="file"/><br>
<button type="submit" name="sub" id="sub">提交</button>
</form>
</body>
</html>
servlet代码
文件上传测试,上传文件就不保存到本地l。直接向页面返回文件名,返回json格式。
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
List<String> fileName = new ArrayList<>();
boolean ismultipartContent = ServletFileUpload.isMultipartContent(req);
//判断是否是文件上传
if (ismultipartContent) {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
List<FileItem> fileItems = fileUpload.parseRequest(req);
for (FileItem fileItem : fileItems) {
//判断字段的类型
if (fileItem.isFormField()) {
//处理普通字段
} else{
//文件字段,处理上传字段,这里就不把文件保存到本地了
fileName.add(fileItem.getName());
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
//将list转化为json
int index = 1;
JSONArray jsonArray = new JSONArray();
for (String s : fileName){
JSONObject jsonObject = new JSONObject();
jsonObject.put("file",s);
jsonArray.put(jsonObject);
}
resp.getWriter().print(jsonArray);
}
测试
选择上传的文件
文件上传测试和返回json格式的文件名成功!!