package com.yellow.web.servlet;
import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.time.LocalDate; import java.util.List; import java.util.UUID;
@WebServlet ( "/upload" ) public class UploadServlet extends HttpServlet {
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this .doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean multipartContent = ServletFileUpload.isMultipartContent(req); if (multipartContent){ DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold( 1024 * 1024 ); String temp = req.getServletContext().getRealPath( "/temp" ); System.out.println( "temp = " + temp); File temppath = new File(temp); if (!temppath.exists()){ temppath.mkdirs(); } factory.setRepository(temppath); ServletFileUpload sfu = new ServletFileUpload(factory);
try { List<FileItem> items = sfu.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()){ String fileName = item.getName(); fileName=fileName.substring(fileName.lastIndexOf( "\\" )+ 1 ); fileName=UUID.randomUUID()+ "_" + fileName; LocalDate ld = LocalDate.now(); int year = ld.getYear(); int month = ld.getMonthValue(); int day = ld.getDayOfMonth(); String upload=req.getServletContext().getRealPath( "/upload" ); upload=upload+ "/" +year+ "/" +month+ "/" +day; System.out.println( "upload = " + upload); File uploadpath = new File(upload); if (!uploadpath.exists()){ uploadpath.mkdirs(); } File uploadFile = new File(uploadpath,fileName); System.out.println( "uploadFile = " + uploadFile.getAbsolutePath()); if (!uploadFile.exists()){ uploadFile.createNewFile(); }
item.write(uploadFile); } item.delete();
} } catch (Exception e) { e.printStackTrace(); } }
jsp代码 ------------------- [mw_shl_code=html, true ]<%@ page contentType= "text/html;charset=UTF-8" language= "java" %> <!DOCTYPE html> <html lang= "en" > <head> <meta charset= "UTF-8" > <title>Title</title> </head> <body> <form action= "${pageContext.request.contextPath}/upload" enctype= "multipart/form-data" method= "post" > <input type= "file" name= "photo" ><br> <input type= "submit" value= "上传" > </form> </body> </html> |