此篇文章为文件上传,使用NIO提高性能读写速度,因项目需要因此是查找网上资源并进行相应的修改的Demo,程序已验证可以正常执行,希望对各位有一定帮助。
以上为Demo的目录结构,项目名请修改为efg若设置其他名字,请一并修改web.xml中的"<display-name>efg</display-name>",包名请设置为com.abc.util,若设置为其他包名,请一并修改web.xml中的“<servlet-class>com.abc.util.UploadHandleServlet2</servlet-class>”包名部分。
1.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>efg</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>fileUp</servlet-name>
<servlet-class>com.abc.util.UploadHandleServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUp</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
2.index.jsp 文件上传页面
< page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"gt;
<!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>Insert title here</title>
</head>
<body>
<div>
<h3>文件上传</h3>
<form action="${pageContext.request.contextPath }/fileUp.do" method="post" enctype="multipart/form-data">
<div>
<p>
上传人姓名:<input type="text" name="username">
</p>
<p>
上传文件1:<input type="file" name="file1">
</p>
<p>
上传文件2:<input type="file" name="file2">
</p>
<p>
提交:<input type="submit" value="提交">
</p>
</div>
</form>
</div>
</body>
</html>
3.message.jsp 上传后返回信息页面
< page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"gt;
<!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>Insert title here</title>
</head>
<body>
${message }
</body>
</html>
4.UploadHandleServlet 核心功能类 如修改包名请再同步修改类中的packge
package com.abc.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
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.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadHandleServlet2 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
File tempFile = new File(tempPath);
if (!tempFile.exists() && !tempFile.isDirectory()) {
tempFile.mkdirs();
}
String message = "";
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD * 10);
diskFileItemFactory.setRepository(tempFile);
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
servletFileUpload.setHeaderEncoding("UTF-8");
if (!ServletFileUpload.isMultipartContent(request)) {
request.setAttribute("message", "表单的enctype非文件上传方式!");
request.getRequestDispatcher("/WEB-INF/jsp/message.jsp").forward(request, response);
return;
}
servletFileUpload.setFileSizeMax(1024 * 1024);
servletFileUpload.setSizeMax(1024 * 1024 * 10);
servletFileUpload.setProgressListener(new ProgressListener() {
@Override
public void update(long pBytesRead, long pContentLength, int arg2) {
System.out.println("文件大小为:" + pContentLength + ",当前已处理" + pBytesRead);
}
});
try {
List<FileItem> fileItems = servletFileUpload.parseRequest(request);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
System.out.println(name + ":" + value);
} else {
String fileName = fileItem.getName();
if (fileName == null || fileName.trim().equals("")) {
continue;
}
fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);
if ("rar".equals(fileExtName) || "tar".equals(fileExtName) || "zip".equals(fileExtName)
|| "jar".equals(fileExtName)) {
request.setAttribute("message", "文件格式错误!");
request.getRequestDispatcher("/WEB-INF/jsp/message.jsp").forward(request, response);
return;
}
InputStream is = fileItem.getInputStream();
fileName = mkFileName(fileName);
String savePathStr = mkFilePath(savePath, fileName);
FileOutputStream fos = new FileOutputStream(savePathStr+File.separator+fileName);
ReadableByteChannel readChannel = Channels.newChannel(is);
WritableByteChannel writeChannel = Channels.newChannel(fos);
ByteBuffer buffer = ByteBuffer.allocate(1024);
int len = 0;
while (true) {
buffer.clear();
len = readChannel.read(buffer);
if (len < 0) {
break;
}
buffer.flip();
writeChannel.write(buffer);
}
is.close();
fos.close();
readChannel.close();
writeChannel.close();
fileItem.delete();
message = "文件上传成功!";
}
}
}catch (FileUploadBase.FileSizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("message", "单个文件超出最大值!!!");
request.getRequestDispatcher("/WEB-INF/message.jsp").forward(request, response);
return;
}catch (FileUploadBase.SizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("message", "上传文件的总的大小超出限制的最大值!!!");
request.getRequestDispatcher("/WEN-INF/message.jsp").forward(request, response);
return;
} catch (FileUploadException e) {
e.printStackTrace();
message = "文件上传失败";
}
request.setAttribute("message", message);
request.getRequestDispatcher("/WEB-INF/jsp/message.jsp").forward(request, response);
}
private String mkFileName(String fileName) {
return UUID.randomUUID().toString() + "_" + fileName;
}
private String mkFilePath(String savePath, String fileName) {
int hashcode = fileName.hashCode();
int dir1 = hashcode & 0xf;
int dir2 = (hashcode & 0xf0) >> 4;
String dir = savePath + "\\" + dir1 + "\\" + dir2;
File file = new File(dir);
if (!file.exists()) {
file.mkdirs();
}
return dir;
}
}
参考资料链接:https://www.cnblogs.com/longqingyang/p/5579889.html
后续会再整理文件上传