怎样使用Servlet控制文件上传?
在实际应用中,为了保证系统的安全运行,可能需要对上传的文件进行控制。例如:上传图片时指定图片大小,发送邮件时对附件的类型和大小进行控制等。以下就是一套控制文件类型和大小的案例。
需要使用的jar包:
jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>文件上传</title> </head> <body> <form action="${pageContext.request.contextPath}/uploadServlet" method="post" enctype="multipart/form-data"> <p>用户名:<input name="username"/></p> <p>请选择文件:<input type="file" name="nfile"/></p> <p><input value="上传" type="submit"/></p> </form> </body> </html>
selvlet页面:
@WebServlet(name="UploadServlet",value="/uploadServlet") //servlet3.0 注解配置 public class UploadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("----文件上传---------"); response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); //获取上传文件的路径 String realPath = this.getServletContext().getRealPath("files"); System.out.println("上传路径:"+realPath); //1.创建DiskFileItemFactory DiskFileItemFactory dif = new DiskFileItemFactory(); //2.创建ServletFileUpload 对象 ServletFileUpload sfu = new ServletFileUpload(dif); //3.判断表单提交 是不是 multipart/form-data boolean isMultipart = sfu.isMultipartContent(request); if(isMultipart){ //进行文件上传 //ServletFileUpload 解析请求 获取元素集合 List<String> filTypes = Arrays.asList("jpg","png","gif","bmp"); //限定单个文件的大小 sfu.setSizeMax(1024*30); try { List<FileItem> items = sfu.parseRequest(request); if(items!=null){ for(FileItem item : items){ if(item.isFormField()){ //判断是否是普通字段 String fieldName = item.getFieldName(); String value = item.getString("UTF-8"); System.out.println(fieldName+"---"+value); }else{ //是文件 文件上传 //获取上传的文件名 String fileName = item.getName(); //判断文件类型是否匹配: //获取后缀 String fileType = fileName.substring(fileName.lastIndexOf(".")+1); System.out.println("后缀:"+fileType); boolean flag = filTypes.contains(fileType); if(flag){ System.out.println("上传的文件名:"+fileName); //新建一个文件对象 第一个参数放文件上传路径 File file = new File(realPath, fileName); //开始上传 item.write(file); System.out.println("文件上传成功!"); response.getWriter().print("文件上传成功!"); }else{ response.getWriter().print("上传失败!文件类型必须是jpg,png,gif,bmp!"); } } } } }catch (FileUploadBase.SizeLimitExceededException e) { System.out.println("上传失败,文件太大,单个文件的最大限制是:"+sfu.getSizeMax()+"bytes!"); response.getWriter().print("上传失败,文件太大,单个文件的最大限制是:"+sfu.getSizeMax()+"bytes!"); }catch (Exception e) { e.printStackTrace(); } }else{ response.getWriter().print("表单不是multipart/form-data,文件上传失败!"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
长路漫漫,键盘作伴~