上传文件四大注意事项:
1.保证服务器安全,上传文件应存放在不能直接访问的目录下,比如WEB-INF目录下
2.防止出现文件覆盖现象要确保文件名的唯一性
3.限制文件上传的最大值
4.限制文件上传的类型,判断其合法性
代码所需依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
具体实现代码如下:
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//判断上传的表单是否带有文件
if (!ServletFileUpload.isMultipartContent(req)) {
//不带有文件直接终止
return;
}
//上传文件保存路径 可以放在WEB-INF下 这也可以保证安全性用户不能直接访问
String path = req.getServletContext().getRealPath("/WEB-INF/upload");
//判断文件夹是否存在 不存在就创建
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
//文件过大存放临时文件夹
String tmp = req.getServletContext().getRealPath("/WEB-INF/tmp");
//判断文件夹是否存在 不存在就创建
File tmpFile = new File(tmp);
if (!tmpFile.exists()) {
tmpFile.mkdir();
}
try {
//处理文件和大小限制
DiskFileItemFactory factory = new DiskFileItemFactory();
//当上传大小超过限制时 会存放在临时文件中(可以不设置使用默认值)
factory.setSizeThreshold(1024 * 1024);//1M
factory.setRepository(file);
ServletFileUpload upload = new ServletFileUpload(factory);
//监听文件上传进度
upload.setProgressListener(new ProgressListener() {
@Override
public void update(long uploaded, long totalSize, int i) {
System.out.println("总大小:" + totalSize + "已上传:" + uploaded);
}
});
//设置编码
upload.setHeaderEncoding("UTF-8");
//设置单个文件最大值
upload.setFileSizeMax(1024 * 1024 * 10);//10M
//设置总共上传文件最大值
upload.setSizeMax(1024 * 1024 * 10);//10M
//处理上传的文件 解析前端请求
List<FileItem> fileItems = upload.parseRequest(req);
for (FileItem fileItem : fileItems) {
//如果是普通表单
if (fileItem.isFormField()) {
String fieldName = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
System.out.println(fieldName + ":" + value);
} else {
//如果是文件表单 处理文件
String fileItemName = fileItem.getName();
if (fileItemName.trim().equals("") || fileItemName == null) {
continue;
}
//获取文件名
String filename = fileItemName.substring(fileItemName.lastIndexOf("/") + 1);
//获取后缀
String suffix = filename.substring(filename.lastIndexOf(".") + 1);
String uuidPath = UUID.randomUUID().toString();
String string = LocalDate.now().toString();
String realPath = path +"/"+ string;
File realPathFile = new File(realPath);
if (!realPathFile.exists()) {
realPathFile.mkdir();
}
//获取输入流
InputStream inputStream = fileItem.getInputStream();
//创建输入流
FileOutputStream outputStream = new FileOutputStream(realPath + "/" + uuidPath + "." + suffix);
//创建缓冲区
byte[] bytes = new byte[1024 * 1024];
int len = 0;
while ((len = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, len);
}
//关闭流
outputStream.close();
inputStream.close();
//上传成功 清除临时文件
fileItem.delete();
}
}
req.setAttribute("msg", "上传成功!");
req.getRequestDispatcher("/result.jsp").forward(req, resp);
} catch (FileUploadException e) {
req.setAttribute("msg", "上传失败!");
req.getRequestDispatcher("/result.jsp").forward(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}