文件上传
1. 建upload.jsp
<form action="<%=request.getContextPath()%>/upload"method="post" enctype="multipart/form-data">
<input type="file"name="file"/>
<input type="submit"value="提交"/>
</form>
2. 建UploadServlet.class
publicclass UploadServlet extends HttpServlet {
// 服务器地址
private String serverPath = null;
// 文件上传目录,根据不同的操作系统要判断斜杠的方向
private String uploadPath ="upload/";
// 允许操作的文件类型
private String[] types = { "png","jpg", "txt" };
@Override
protected void service(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
// 获取服务器地址
serverPath =req.getSession().getServletContext().getRealPath("/");
//System.out.println(req.getSession().getServletContext());
System.out.println(serverPath);
// 如果文件目录不存在则去创建
if (!new File(serverPath +uploadPath).exists()) {
new File(serverPath +uploadPath).mkdirs();
}
DiskFileItemFactory factory = newDiskFileItemFactory();
// 设置文件的最大缓存
factory.setSizeThreshold(5 * 1024);
// 文件上传核心类
ServletFileUpload upload = newServletFileUpload(factory);
// 设置文件最大大小
upload.setFileSizeMax(3 * 1024 *1024);
String filePath = null;
try {
// 解析请求,获取上传的文件对象列表
List<FileItem> items =upload.parseRequest(req);
for (FileItem item : items){
// 判断item是简单的数据还是文件,该方法如果返回false,说明是一个文件
if(!item.isFormField()) {
// 获取文件名
StringfileName = item.getName();
// 获取文件类型
Stringtype = fileName
.substring(fileName.lastIndexOf(".")+ 1);
// 判断文件类型是否合法
if(Arrays.asList(types).contains(type)) {
//文件上传
Stringuuid = UUID.randomUUID().toString().replace("-",
"");
//真正的文件上传路径
filePath= serverPath + uploadPath + uuid + "." + type;
//System.out.println(filePath);
item.write(newFile(filePath));
} else {
thrownew RuntimeException("不是合法的文件类型");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
3. 在web.xml中进行配置
<servlet>
<servlet-name>uploadServlet</servlet-name>
<servlet-class>com.niit.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>