1.创建文件上传页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
文件:<input type="file" name="file1"/><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2.文件上传Servlet
package com.whoami.servlet;
import com.whoami.utils.UploadUtils;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
@WebServlet(name = "UploadController",value = "/upload")
@MultipartConfig(maxFileSize = 1024*1024*100,maxRequestSize = 1024*1024*200)
public class UploadController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
Part part = request.getPart("file1");
String uploadPath = request.getServletContext().getRealPath("/WEB-INF/upload");
File file = new File(uploadPath);
if(!file.exists()){
file.mkdir();
}
String oldName = part.getSubmittedFileName();
String newName = UploadUtils.newFileName(oldName);
part.write(uploadPath+"\\"+newName);
response.getWriter().println(part.getSubmittedFileName()+"上传成功!!");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
3.生成唯一的文件名
package com.whoami.utils;
import java.util.UUID;
public class UploadUtils {
public static String newFileName(String filename){
return UUID.randomUUID().toString().replace("-","")+"_"+filename;
}
}
4.上传结果
我把文件存到了项目的WEB-INF/upload下面