${msg }

当前位置:   article > 正文

Javaweb 图片上传格式以及尺寸大小的限制_java怎么限制图片格式

java怎么限制图片格式

首先需要上传图片的jsp页面是这样的,从选择文件这里选择图片.

下面是jsp的部分页面.

  1. <body>
  2. <div>
  3. <p style="font-weight: 900; color: red;">${msg }</p>
  4. <form action="<c:url value='/admin/AdminAddBookServlet'/>" enctype="multipart/form-data" method="post" id="form">
  5. <div>
  6. <ul>
  7. <li>书名: <input id="bname" type="text" name="bname" value="Spring实战(第3版)(In Action系列中最畅销的Spring图书,近十万读者学习Spring的共同选择)" style="width:500px;"/></li>
  8. <li>大图: <input id="image_w" type="file" name="image_w"/></li>
  9. <li>小图: <input id="image_b" type="file" name="image_b"/></li>
  10. <li>当前价:<input id="price" type="text" name="price" value="40.7" style="width:50px;"/></li>
  11. <li>定价: <input id="currPrice" type="text" name="currPrice" value="59.0" style="width:50px;"/>
  12. 折扣:<input id="discount" type="text" name="discount" value="6.9" style="width:30px;"/></li>
  13. </ul>
  14. <hr style="margin-left: 50px; height: 1px; color: #dcdcdc"/>
  15. <table>
  16. <tr>
  17. <td colspan="3">
  18. 作者:  <input type="text" id="author" name="author" value="Craig Walls" style="width:150px;"/>
  19. </td>
  20. </tr>
  21. <tr>
  22. <td colspan="3">
  23. 出版社: <input type="text" name="press" id="press" value="人民邮电出版社" style="width:200px;"/>
  24. </td>
  25. </tr>
  26. <tr>
  27. <td colspan="3">出版时间:<input type="text" id="publishtime" name="publishtime" value="2013-6-1" style="width:100px;"/></td>
  28. </tr>
  29. <tr>
  30. <td>版次:  <input type="text" name="edition" id="edition" value="1" style="width:40px;"/></td>
  31. <td>页数:  <input type="text" name="pageNum" id="pageNum" value="374" style="width:50px;"/></td>
  32. <td>字数:  <input type="text" name="wordNum" id="wordNum" value="48700" style="width:80px;"/></td>
  33. </tr>
  34. <tr>
  35. <td width="250">印刷时间:<input type="text" name="printtime" id="printtime" value="2013-6-1" style="width:100px;"/></td>
  36. <td width="250">开本:  <input type="text" name="booksize" id="booksize" value="16" style="width:30px;"/></td>
  37. <td>纸张:  <input type="text" name="paper" id="paper" value="胶版纸" style="width:80px;"/></td>
  38. </tr>
  39. <tr>
  40. <td>
  41. 一级分类:<select name="pid" id="pid" onchange="loadChildren()">
  42. <option value="">==请选择1级分类==</option>
  43. <c:forEach items="${parents}" var="parent">
  44. <option value="${parent.cid}">${parent.cname}</option>
  45. </c:forEach>
  46. </select>
  47. </td>
  48. <td>
  49. 二级分类:<select name="cid" id="cid">
  50. <option value="">==请选择2级分类==</option>
  51. </select>
  52. </td>
  53. <td></td>
  54. </tr>
  55. <tr>
  56. <td>
  57. <input type="button" id="btn" class="btn" value="新书上架">
  58. </td>
  59. <td></td>
  60. <td></td>
  61. </tr>
  62. </table>
  63. </div>
  64. </form>
  65. </div>
  66. </body>

下面是servlet中的限制图片尺寸,格式的代码.

  1. package cn.itcast.goods.admin.book.web.servlet;
  2. import java.awt.Image;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import javax.swing.ImageIcon;
  14. import org.apache.commons.fileupload.FileItem;
  15. import org.apache.commons.fileupload.FileItemFactory;
  16. import org.apache.commons.fileupload.FileUploadException;
  17. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  18. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  19. import cn.itcast.commons.CommonUtils;
  20. import cn.itcast.goods.book.domain.Book;
  21. import cn.itcast.goods.book.service.BookService;
  22. import cn.itcast.goods.category.domain.Category;
  23. public class AdminAddBookServlet extends HttpServlet {
  24. public void doPost(HttpServletRequest request, HttpServletResponse response)
  25. throws ServletException, IOException {
  26. request.setCharacterEncoding("utf-8");
  27. response.setContentType("text/html;charset=utf-8");
  28. /*
  29. * 1. commons-fileupload的上传三步
  30. */
  31. FileItemFactory factory = new DiskFileItemFactory(); //disk...Factory这个构造器可以给参数(缓存大小 or 缓存目录),不给缓存大小就是 10KB
  32. /*
  33. * 2.创建解析器对象
  34. */
  35. ServletFileUpload sfu = new ServletFileUpload(factory);
  36. sfu.setFileSizeMax(80 * 1024); //设置单个上传的文件上限为 80KB
  37. /*
  38. * 3.解析request得到List<FileItem>
  39. */
  40. List<FileItem> fileItemList = null(此处写空Null,不知道为什么浏览器没显示);
  41. try {
  42. fileItemList = sfu.parseRequest(request);
  43. } catch (FileUploadException e) {
  44. //如果出现这个异常,说明单个文件超出了 80 KB
  45. error("上传的文件超出了80KB", request, response);
  46. return;
  47. }
  48. /*
  49. * 4.把List<FileItem>封装到book对象中
  50. * 4.1首先把"普通表单字段"放到一个map中,再把map转换成book和category对象,再建立两者的关系.
  51. */
  52. Map<String, Object> map = new HashMap<String, Object>();
  53. for(FileItem fileItem : fileItemList){
  54. if(fileItem.isFormField()){ //如果是普通表单字段
  55. map.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
  56. }
  57. }
  58. Book book = CommonUtils.toBean(map, Book.class); //把Map中的大部分数据封装到book对象中
  59. Category category = CommonUtils.toBean(map, Category.class); //把map中的cid封装到category中
  60. book.setCategory(category);
  61. /*
  62. * 4.2把上传的图片保存起来
  63. * >获取文件名:截取之
  64. * >给文件添加前缀:使用uuid前缀,为了避免文件同名现象
  65. * >校验文件的扩展名:只能是jpg
  66. * >校验图片的尺寸
  67. * >指定图片的保存路径,这需要使用ServletContext#getRealPath()
  68. * >保存之
  69. * >把图片的路径设置给book对象
  70. */
  71. //获取文件名
  72. FileItem fileItem = fileItemList.get(1); //获取大图
  73. String filename = fileItem.getName();
  74. //截取文件名,因为部分浏览器上传的是绝对路径
  75. int index = filename.lastIndexOf("\\");
  76. if(index !=-1){
  77. filename = filename.substring(index + 1);
  78. }
  79. //给文件名添加uuid的前缀,避免文件重名现象
  80. filename = CommonUtils.uuid() + "_" + filename;
  81. //校验文件的扩展名
  82. if(!filename.toLowerCase().endsWith(".jpg")){ //将大写转换成小写进行比较
  83. error("上传的图片扩展名必须是JPG", request, response);
  84. return;
  85. }
  86. //校验图片的尺寸
  87. //保存上传的图片,把图片new成图片对象: Image,Icon,ImageIcon,BufferedImage,ImageIO
  88. /*
  89. *保存图片:
  90. *1.获取真实路径
  91. */
  92. String savepath = this.getServletContext().getRealPath("/book_img");
  93. /*
  94. * 2.创建目标文件
  95. */
  96. File destFile = new File(savepath,filename);
  97. /*
  98. * 3.保存文件
  99. */
  100. try {
  101. fileItem.write(destFile);//它会把临时文件重定向到指定的路径,再删除临时文件
  102. } catch (Exception e) {
  103. throw new RuntimeException(e);
  104. }
  105. //校验尺寸
  106. //1.使用文件路径创建ImageIcon
  107. ImageIcon icon = new ImageIcon(destFile.getAbsolutePath());
  108. //2.通过ImageIcon得到Image对象
  109. Image image = icon.getImage();
  110. //3.获取宽高来进行校验
  111. if(image.getWidth(null)>350 || image.getHeight(null)>350){
  112. error("您上传的图片尺寸超出了350*350像素!", request, response);
  113. destFile.delete(); //删除图片
  114. return;
  115. }
  116. //把图片的路径设置给book对象
  117. book.setImage_w("book_img/" + filename);
  118. //获取文件名
  119. fileItem = fileItemList.get(2); //获取小图
  120. filename = fileItem.getName();
  121. //截取文件名,因为部分浏览器上传的是绝对路径
  122. index = filename.lastIndexOf("\\");
  123. if(index !=-1){
  124. filename = filename.substring(index + 1);
  125. }
  126. //给文件名添加uuid的前缀,避免文件重名现象
  127. filename = CommonUtils.uuid() + "_" + filename;
  128. //校验文件的扩展名
  129. if(!filename.toLowerCase().endsWith(".jpg")){
  130. error("上传的图片扩展名必须是JPG", request, response);
  131. return;
  132. }
  133. //校验图片的尺寸
  134. //保存上传的图片,把图片new成图片对象: Image,Icon,ImageIcon,BufferedImage,ImageIO
  135. /*
  136. *保存图片:
  137. *1.获取真实路径
  138. */
  139. savepath = this.getServletContext().getRealPath("/book_img");
  140. /*
  141. * 2.创建目标文件
  142. */
  143. destFile = new File(savepath,filename);
  144. /*
  145. * 3.保存文件
  146. */
  147. try {
  148. fileItem.write(destFile);//它会把临时文件重定向到指定的路径,再删除临时文件
  149. } catch (Exception e) {
  150. throw new RuntimeException(e);
  151. }
  152. //校验尺寸
  153. //1.使用文件路径创建ImageIcon
  154. icon = new ImageIcon(destFile.getAbsolutePath());
  155. //2.通过ImageIcon得到Image对象
  156. image = icon.getImage();
  157. //3.获取宽高来进行校验
  158. if(image.getWidth(null)>350 || image.getHeight(null)>350){
  159. error("您上传的图片尺寸超出了350*350像素!", request, response);
  160. destFile.delete(); //删除图片
  161. return;
  162. }
  163. //把图片的路径设置给book对象
  164. book.setImage_b("book_img/" + filename);
  165. //调用service完成保存
  166. book.setBid(CommonUtils.uuid());
  167. BookService bookService = new BookService();
  168. bookService.add(book);
  169. //保存成功信息转发到msg.jsp
  170. request.setAttribute("msg", "添加图书成功!");
  171. request.getRequestDispatcher("/adminjsps/msg.jsp").forward(request, response);
  172. }
  173. /*
  174. * 保存错误信息,转发到add.jsp
  175. */
  176. private void error(String msg, HttpServletRequest request, HttpServletResponse response)
  177. throws ServletException, IOException {
  178. request.setAttribute("msg", msg);
  179. request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response);
  180. }
  181. }

下面是bookservice的添加方法.

  1. public class BookService {
  2. private BookDao bookDao = new BookDao();
  3. /**
  4. * 添加图书
  5. * @param book
  6. */
  7. public void add(Book book){
  8. try {
  9. bookDao.add(book);
  10. } catch (SQLException e) {
  11. // TODO Auto-generated catch block
  12. throw new RuntimeException(e);
  13. }
  14. }
  15. }

下面是bookDao的sql代码.

  1. public class BookDao {
  2. private QueryRunner qr = new TxQueryRunner();
  3. /**
  4. * 添加图书
  5. * @param book
  6. * @throws SQLException
  7. */
  8. public void add(Book book) throws SQLException {
  9. String sql = "insert into t_book(bid,bname,author,price,currPrice,"+
  10. "discount,press,publishtime,edition,pageNum,wordNum,printtime,"+
  11. "booksize,paper,cid,image_w,image_b)"+
  12. "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
  13. Object[] params = {book.getBid(),book.getBname(),book.getAuthor(),
  14. book.getPrice(),book.getCurrPrice(),book.getDiscount(),
  15. book.getPress(),book.getPublishtime(),book.getEdition(),
  16. book.getPageNum(),book.getWordNum(),book.getPrinttime(),
  17. book.getBooksize(),book.getPaper(),book.getCategory().getCid(),
  18. book.getImage_w(),book.getImage_b()};
  19. qr.update(sql,params);
  20. }
  21. }
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签