Java工具之上传文件
4个代码
1、前端JSP
2、自定义异常类
3、文件上传抽象类
4、Servlet
1.JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件上传</title> </head> <body> <h3>文件上传</h3> <span style="color: red">${errorMsg}</span> <form action="/upload" method="post" enctype="multipart/form-data"> 账号:<input type="text" name="username"/><br> 邮箱:<input type="email" name="email"><br> 头像:<input type="file" name="headimg"><br> <input type="submit" value="注册"> </form> </body> </html>
2.自定义异常类
package com.vae.Upload; public class LogicException extends RuntimeException{ /** * * @param message 异常的信息,可以自定义的 */ public LogicException(String message) { super(message); } /** * * @param message 异常的信息 * @param cause 异常的根本原因 */ public LogicException(String message, Throwable cause) { super(message, cause); } }
3.文件上传的抽象类
package com.vae.Upload; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FilenameUtils; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.UUID; public class FileUtil { //设置允许接收的文件的格式,我这里设置为只能是图片 private static final String ALLWED_IMAGE_TYPE ="png,jpg,gif,jpeg"; public static void upload(HttpServletRequest req) { //解析和检查请求,是否是post方式,默认是二进制流格式 Boolean isMultipart=ServletFileUpload.isMultipartContent(req); if (!isMultipart) { return; //如果不是就不用上传了 } try { //创建FileItemFactory对象 FileItemFactory factory=new DiskFileItemFactory(); //设置缓存区大小,默认大小是10kb, ((DiskFileItemFactory) factory).setSizeThreshold(20*1024); //设置临时目录,默认是Tomcat下的temp,不建议设置 //((DiskFileItemFactory) factory).setRepository(临时目录不建议修改); //创建文件上传的处理器 ServletFileUpload upload=new ServletFileUpload(factory); //单个文件上传大小限制为2M upload.setFileSizeMax(1024*1024*2); //这次请求上传文件的大小(整个表单)限制为3M upload.setSizeMax(1024*1024*3); //解析请求 List<FileItem> items=upload.parseRequest(req); //迭代出每一个FileItem for (FileItem item : items) { String fileName = item.getFieldName(); if (item.isFormField()) { //普通的表单控件 String value = item.getString("utf-8"); System.out.println(fileName + "->" + value); } else { //----------------先获取上传文件的拓展名 String ext = FilenameUtils.getExtension(item.getName()); String [] allowedImagetype=ALLWED_IMAGE_TYPE.split(","); //-----------------判断上传文件的拓展名在不在我设定的范围之内,不在的话提醒并且结束方法 if (!Arrays.asList(allowedImagetype).contains(ext)) { throw new LogicException("你上传的不是图片,请重新上传图片"); } //上传文件的控件 String RandomName = UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(item.getName()); System.out.println(fileName + "->" + FilenameUtils.getName(item.getName())); //一个的标签的name,一个是文件的name String path=req.getServletContext().getRealPath("/upload"); System.out.println(path); item.write(new File(path, RandomName)); //把上传的文件保存到某个文件中 //System.out.println(item.isInMemory());//判断文件资源是否在内存中 } } } catch (FileUploadBase.FileSizeLimitExceededException e){ throw new LogicException("单个文件的上传大小不得超过2M"); } catch (FileUploadBase.SizeLimitExceededException e){ throw new LogicException("所有上传文件的大小不得超过3M"); } //Exception会捕捉我们的LogicException异常提示,所以我们在上面写一个,便于把LogicException异常返回给Servlet catch (LogicException e){ throw e; } catch (Exception e) { e.printStackTrace(); } } }
4.Servlet
package com.vae.Upload; 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.IOException; @WebServlet("/upload") public class UploadServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { FileUtil.upload(req); }catch (LogicException e){ //拿到我们的LogicException异常信息 String Msg=e.getMessage(); req.setAttribute("errorMsg",Msg); req.getRequestDispatcher("/input.jsp").forward(req,resp); } } }