【转】JSP使用上传文件,并生产高清缩略图示例

原文地址:http://blog.csdn.net/yakson/article/details/9875731

前言

刚开始本来只想来测试一下Thumbnails生成缩略图的效果的,顺便来学一下jsp文件,开始没有使用commons-fileupload上 传组件,自己用纯jsp代码来编写,过程相当曲折。所以就不建议大家去编写纯JSP的上传代码了,想写的可以参考下commons-fileupload 的源码,里面很详细。

一、JSP上传文件

大家都知道,上传文件是以二进制上传的,这样可以让文件上传,所以JSP要做到将文件以二进制上传,我们再HTML的表单提交时就要设置enctype="multipart/form-data",这个大家应该都很清楚了。

首先我先将jar包引用列出来,大家先找好这几个jar文件,引入项目

commons-fileupload-1.2.2.jar

commons-io-2.0.1.jar

thumbnailator-0.4.2.jar

先上一下上传页面的JSP代码,其实很简单,放一个file文件选择框就可以,我为了测试,顺便加了一个文本框。

index.jsp

  1. <%@page contentType="text/html" pageEncoding="UTF-8"%>  
  2. <!DOCTYPE html>  
  3. <html>  
  4.     <head>  
  5.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  6.         <title>缩略图生成示例</title>  
  7.     </head>  
  8.     <body>  
  9.         <h1>上传图片</h1>  
  10.         <form name="uploadForm" action="upload.jsp" method="post"  
  11.               enctype="multipart/form-data">  
  12.             <input type="text" name="name" />  
  13.             <input type="file" name="imgPath" />  
  14.             <input type="submit" value="提交" />  
  15.         </form>  
  16.     </body>  
  17. </html>  


二、编写上传文件代码

upload.jsp

  1. <%@page import="net.coobird.thumbnailator.Thumbnails"%>  
  2. <%@page import="org.apache.commons.fileupload.FileItem"%>  
  3. <%@page import="java.util.Iterator"%>  
  4. <%@page import="java.util.Hashtable"%>  
  5. <%@page import="java.util.Map"%>  
  6. <%@page import="org.apache.commons.fileupload.FileUploadException"%>  
  7. <%@page import="java.util.List"%>  
  8. <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>  
  9. <%@page import="org.apache.commons.fileupload.FileItemFactory"%>  
  10. <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>  
  11. <%@page import="java.io.File"%>  
  12. <%@page contentType="text/html" pageEncoding="UTF-8"%>  
  13. <!DOCTYPE html>  
  14. <html>  
  15.     <head>  
  16.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  17.         <title>JSP Page</title>  
  18.     </head>  
  19.     <body>  
  20.         <%  
  21.             request.setCharacterEncoding("UTF-8");  
  22.             String name = "";  
  23.             String imgPath = "";  
  24.             String filePath = "";  
  25.             if (ServletFileUpload.isMultipartContent(request)) {  
  26.                 try {  
  27.                     FileItemFactory factory = new DiskFileItemFactory();  
  28.                     ServletFileUpload upload = new ServletFileUpload(factory);  
  29.                     upload.setHeaderEncoding("UTF-8");  
  30.                     upload.setFileSizeMax(1024000L);//单个上传文件最大值  
  31.                     upload.setSizeMax(2048000L);//整个请求的大小最大值  
  32.                     List list = upload.parseRequest(request);  
  33.                     Map _fields = new Hashtable();  
  34.                     Iterator it = list.iterator();  
  35.                     String tempPath = request.getRealPath("/temp/");  
  36.   
  37.                     String UUID = java.util.UUID.randomUUID().toString();  
  38.   
  39.                     while (it.hasNext()) {  
  40.                         FileItem item = (FileItem) it.next();  
  41.                         if (!item.isFormField()) {  
  42.                             String fileImg = item.getName();  
  43.                             //获取图片后缀  
  44.                             String suffix = fileImg.substring(fileImg.lastIndexOf(".")  
  45.                                                                     , fileImg.length());  
  46.                             filePath = tempPath + File.separator + UUID + suffix;  
  47.                             // 建立目标文件  
  48.                             File file = new File(filePath);  
  49.                             //将文件写入到临时文件上传目录  
  50.                             item.write(file);  
  51.                             _fields.put(item.getFieldName(), UUID + suffix);  
  52.                         } else {  
  53.                             _fields.put(item.getFieldName(), item.getString());  
  54.                         }  
  55.                     }  
  56.                     name = _fields.get("name").toString();  
  57.                     imgPath = _fields.get("imgPath").toString();  
  58.                     String imgPath_s = imgPath.substring(0, imgPath.lastIndexOf("."));  
  59.                     String imgPath_s_suffix = imgPath.substring(imgPath.lastIndexOf(".")  
  60.                                                                 , imgPath.length());  
  61.                     //生成缩略图  
  62.                     String filePath_s_w = tempPath + File.separator + imgPath_s  
  63.                                            + "_w" + imgPath_s_suffix;  
  64.                     String filePath_s_h = tempPath + File.separator + imgPath_s  
  65.                                            + "_h" + imgPath_s_suffix;  
  66.                     String filePath_s_m = tempPath + File.separator + imgPath_s  
  67.                                            + "_m" + imgPath_s_suffix;  
  68.                     //宽为准  
  69.                     Thumbnails.of(filePath)  
  70.                             .size(300, 200)  
  71.                             .toFile(filePath_s_w);  
  72.                     //中图  
  73.                     Thumbnails.of(filePath)  
  74.                             .size(500, 400)  
  75.                             .toFile(filePath_s_m);  
  76.                     //高为准  
  77.                     Thumbnails.of(filePath)  
  78.                             .size(200, 300)  
  79.                             .toFile(filePath_s_h);  
  80.                 } catch (Exception e) {  
  81.                     out.write(e.getMessage());  
  82.                     e.printStackTrace();  
  83.                 }  
  84.             } else {  
  85.                 name = request.getParameter("name");  
  86.                 imgPath = request.getParameter("imgPath");  
  87.             }  
  88.         %>  
  89.         name:<%=name%><br />  
  90.         imgPath<%=imgPath%><br />  
  91.     </body>  
  92. </html>  


我就代码简单说明一下,我们用ServletFileUpload.isMultipartContent(request)来判断用户的表单是否是以二 进制上传,从而改变获取提交表单数据的模式,因为从二进制里提交的表单,你从request.getParameter中是获取不到值的。

通过commons-fileupload组建,我们很容易的获取到了用户表单上传文件流,并保持到了我们服务器磁盘中。

此示例组要是测试图片生成缩略图,所以就没考虑上传的文件类型,我就当上传的图片类型了,如果上传其他类型的文件,页面会异常,但是文件可以上传的。

好我们来看下生成缩略图的代码,仅仅简单的一行代码。

  1. //size(宽度, 高度)     
  2.     
  3. /*     
  4.  * 若图片横比200小,高比300小,不变     
  5.  * 若图片横比200小,高比300大,高缩小到300,图片比例不变     
  6.  * 若图片横比200大,高比300小,横缩小到200,图片比例不变     
  7.  * 若图片横比200大,高比300大,图片按比例缩小,横为200或高为300     
  8.  */      
  9. Thumbnails.of("c:/images/1280x1024.jpg")      
  10.         .size(200, 300)     
  11.         .toFile("c:/200x300.jpg");    

相信代码意思已经不用解释了,关于Thumbnails的其他用法,大家还是去官方网站上查看吧,下载的示例和文档中有详细的说明。

在谷歌开源项目中开源找到地址:

http://code.google.com/p/thumbnailator/downloads/list

如果需要我做的示例的项目源码,留言时写下你的邮箱,我看到会把源码发到你的邮箱。

最后附上项目结构截图:

posted @ 2016-01-04 22:06  dirgo  阅读(426)  评论(0编辑  收藏  举报