1、为保证服务器安全,上传文件应该放在外界无法直接访问的目录下,比如放于WEB-INF目录下。
2、为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名。
3、为防止一个目录下面出现太多文件,要使用hash算法打散存储。
4、要限制上传文件的最大值。
5、要限制上传文件的类型,在收到上传文件名时,判断后缀名是否合法。
@WebServlet(value = “/UpdateServlet”)
@MultipartConfig(maxFileSize = 510241024,maxRequestSize =5010241024 )
public class UpdateServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接受文件
request.setCharacterEncoding(“utf-8”);
response.setContentType(“text/html;charset=utf-8”);
PrintWriter out = response.getWriter();
Collection parts = request.getParts();
String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
File file = new File(realPath);
if (!file.exists()){
file.mkdirs();
}
if (parts!=null){
for (Part part : parts) {
if (part.getSubmittedFileName()!=null){
String header = part.getHeader("content-disposition");
String path = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
String filename1=path.substring(path.lastIndexOf("\\")+1);
if (filename1==""){
continue;
}
String filename= filename1.substring(filename1.lastIndexOf(".") + 1);
List<String> allows = Arrays.asList("jpg","txt","png");
if (!allows.contains(filename)){
out.write("文件类型不支持"+filename1);
return;
}
System.out.println(filename1);
part.write(Utirls.getfilePath(realPath,filename1)+"/"+Utirls.getNewName(filename1)+"_"+filename1);
part.delete();
out.print("<h1>"+filename1+"上传成功</h1>");
}
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebServlet(value = “/FileListServlet”)
public class FileListServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
System.out.println(realPath);
HashMap<String,String> map = new HashMap<>();
Utirls.ListFile(new File(realPath),map);
request.setAttribute(“map”,map);
request.getRequestDispatcher("/map.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
<%–
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/9/4 0004
Time: 14:34
To change this template use File | Settings | File Templates.
–%>
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
文件1:
文件2:
<%–
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/9/4 0004
Time: 17:21
To change this template use File | Settings | File Templates.
–%>
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
<%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core”%>
public class Utirls {
public static String getNewName(String filename){
String s = UUID.randomUUID().toString();
String replace = s.replace("-", “”);
return replace;
}
public static String getfilePath(String basepath,String filename){
int i = filename.hashCode();
int i1 = i & 0xf;
int i2 = (i & 0xf0) >> 4;
File file = new File(basepath+"/"+i1+"/"+i2);
if (!file.exists()){
file.mkdirs();
}
return basepath+"/"+i1+"/"+i2;
}
public static void ListFile(File file, HashMap<String,String> map){
File[] files = file.listFiles();
if (files!=null){
for (File file1 : files) {
if (file1.isDirectory()){
ListFile(file1,map);
}
else{
map.put(file1.getName(), file1.getName().split("_")[1]);
}
}
}
}
}
@WebServlet(value = “/AServlet”)
public class AServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getParameter(“filename”);
String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
String s1 = filename.split("_")[1];
String s = Utirls.getfilePath(realPath, s1);
System.out.println(s);
s=s+"/"+filename;
FileInputStream fis = new FileInputStream(s);
ServletOutputStream outputStream = response.getOutputStream();
response.setHeader(“content-disposition”,“attachment;filenaem=”+URLEncoder.encode(filename,“utf-8”));
byte[] bytes = new byte[1024*7];
int len=-1;
while((len = fis.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
outputStream.close();
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}