JSP使用Common FileUpload组件实现文件上传及限制上传类型实例代码
Java  /  管理员 发布于 7年前   211
1、将commons-fileupload-1.3.3.jar复制到Web应用的lib文件夹下,在WebRoot目录下创建limit.jsp页面,在该页面中添加一个文件域的表单,设置类型为 multipart/form-data。代码如下:
<body> <h2>上传图书课件</h2> <form action="LimitFile" name="one" enctype="multipart/form-data" method="post"> 选择一个rar文件: <input type="file" name="fileupload" value="upload" /> <input type="submit" value="上传"> <input type="reset" value="取消"> </form> </body>
上述代码指定提交后将请求提交给LimitFile处理,LimitFile(Servlet)用来处理上传文件及判断文件类型是否匹配,显示上传结果。
2、创建名为LimitFile的Servlet,并在doPost()方法中编写实现代码,如下所示:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String uploadpath = ""; DiskFileItemFactory factory = new DiskFileItemFactory(); //设置是否使用临时文件保存解析出来的数据的那个临界值,该方法传入参数的单位是字节。 factory.setSizeThreshold(30 * 1024); //用于设置setSizeThreshold()方法中提到的临时文件的存放目录,这里要求使用绝对路径。 factory.setRepository(factory.getRepository()); ServletFileUpload upload = new ServletFileUpload(factory); List list = null; try{ list = upload.parseRequest(request); String[] limit = new String[]{".jpg", ".gif", ".png", ".bmp"}; //定义限制的文件类型 SuffixFileFilter filter = new SuffixFileFilter(limit); //获取SuffixFileFilter实例 Iterator iterator = list.iterator(); while(iterator.hasNext()){ FileItem item =(FileItem)iterator.next(); if(!item.isFormField()){ String filePath = item.getName(); if(filePath != null){File filename= new File(filePath);File uploadFile = new File(request.getSession().getServletContext().getRealPath("/") + "upload");uploadpath = uploadFile.getAbsolutePath()+File.pathSeparator + uploadpath;//因为路径后面多了个";"号,所以要去掉uploadpath = uploadpath.substring(0, uploadpath.length()-1);File saveFile = new File(uploadpath,filename.getName());boolean flag = filter.accept(saveFile);if(flag){ out.print("禁止上传传图片文件"); break;}else{ try { item.write(saveFile); out.print("文件上传成功"); } catch (Exception e) { out.print("文件上传失败了"); e.printStackTrace(); }} } } } }catch(FileUploadException e){ e.printStackTrace(); } }
上述代码在字节串数组limit中定义了不允许上传的文件类型,然后将该数组传递给SuffixFileFilter类的构造函数。在通过该类的accept()方法验证当前上传的文件是否符合条件。最后将文件保存到项目的upload目录下。
总结
以上所述是小编给大家介绍的JSP使用Common FileUpload组件实现文件上传及限制上传类型实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号