首先需要上传图片的jsp页面是这样的,从选择文件这里选择图片.
下面是jsp的部分页面.
<body> <div> <p style="font-weight: 900; color: red;">${msg }</p> <form action="<c:url value='/admin/AdminAddBookServlet'/>" enctype="multipart/form-data" method="post" id="form"> <div> <ul> <li>书名: <input id="bname" type="text" name="bname" value="Spring实战(第3版)(In Action系列中最畅销的Spring图书,近十万读者学习Spring的共同选择)" style="width:500px;"/></li> <li>大图: <input id="image_w" type="file" name="image_w"/></li> <li>小图: <input id="image_b" type="file" name="image_b"/></li> <li>当前价:<input id="price" type="text" name="price" value="40.7" style="width:50px;"/></li> <li>定价: <input id="currPrice" type="text" name="currPrice" value="59.0" style="width:50px;"/> 折扣:<input id="discount" type="text" name="discount" value="6.9" style="width:30px;"/>折</li> </ul> <hr style="margin-left: 50px; height: 1px; color: #dcdcdc"/> <table> <tr> <td colspan="3"> 作者: <input type="text" id="author" name="author" value="Craig Walls" style="width:150px;"/> </td> </tr> <tr> <td colspan="3"> 出版社: <input type="text" name="press" id="press" value="人民邮电出版社" style="width:200px;"/> </td> </tr> <tr> <td colspan="3">出版时间:<input type="text" id="publishtime" name="publishtime" value="2013-6-1" style="width:100px;"/></td> </tr> <tr> <td>版次: <input type="text" name="edition" id="edition" value="1" style="width:40px;"/></td> <td>页数: <input type="text" name="pageNum" id="pageNum" value="374" style="width:50px;"/></td> <td>字数: <input type="text" name="wordNum" id="wordNum" value="48700" style="width:80px;"/></td> </tr> <tr> <td width="250">印刷时间:<input type="text" name="printtime" id="printtime" value="2013-6-1" style="width:100px;"/></td> <td width="250">开本: <input type="text" name="booksize" id="booksize" value="16" style="width:30px;"/></td> <td>纸张: <input type="text" name="paper" id="paper" value="胶版纸" style="width:80px;"/></td> </tr> <tr> <td> 一级分类:<select name="pid" id="pid" onchange="loadChildren()"> <option value="">==请选择1级分类==</option> <c:forEach items="${parents}" var="parent"> <option value="${parent.cid}">${parent.cname}</option> </c:forEach> </select> </td> <td> 二级分类:<select name="cid" id="cid"> <option value="">==请选择2级分类==</option> </select> </td> <td></td> </tr> <tr> <td> <input type="button" id="btn" class="btn" value="新书上架"> </td> <td></td> <td></td> </tr> </table> </div> </form> </div> </body>
下面是servlet中的限制图片尺寸,格式的代码.
package cn.itcast.goods.admin.book.web.servlet; import java.awt.Image; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.swing.ImageIcon; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import cn.itcast.commons.CommonUtils; import cn.itcast.goods.book.domain.Book; import cn.itcast.goods.book.service.BookService; import cn.itcast.goods.category.domain.Category; public class AdminAddBookServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); /* * 1. commons-fileupload的上传三步 */ FileItemFactory factory = new DiskFileItemFactory(); //disk...Factory这个构造器可以给参数(缓存大小 or 缓存目录),不给缓存大小就是 10KB /* * 2.创建解析器对象 */ ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setFileSizeMax(80 * 1024); //设置单个上传的文件上限为 80KB /* * 3.解析request得到List<FileItem> */ List<FileItem> fileItemList = null(此处写空Null,不知道为什么浏览器没显示); try { fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { //如果出现这个异常,说明单个文件超出了 80 KB error("上传的文件超出了80KB", request, response); return; } /* * 4.把List<FileItem>封装到book对象中 * 4.1首先把"普通表单字段"放到一个map中,再把map转换成book和category对象,再建立两者的关系. */ Map<String, Object> map = new HashMap<String, Object>(); for(FileItem fileItem : fileItemList){ if(fileItem.isFormField()){ //如果是普通表单字段 map.put(fileItem.getFieldName(), fileItem.getString("UTF-8")); } } Book book = CommonUtils.toBean(map, Book.class); //把Map中的大部分数据封装到book对象中 Category category = CommonUtils.toBean(map, Category.class); //把map中的cid封装到category中 book.setCategory(category); /* * 4.2把上传的图片保存起来 * >获取文件名:截取之 * >给文件添加前缀:使用uuid前缀,为了避免文件同名现象 * >校验文件的扩展名:只能是jpg * >校验图片的尺寸 * >指定图片的保存路径,这需要使用ServletContext#getRealPath() * >保存之 * >把图片的路径设置给book对象 */ //获取文件名 FileItem fileItem = fileItemList.get(1); //获取大图 String filename = fileItem.getName(); //截取文件名,因为部分浏览器上传的是绝对路径 int index = filename.lastIndexOf("\\"); if(index !=-1){ filename = filename.substring(index + 1); } //给文件名添加uuid的前缀,避免文件重名现象 filename = CommonUtils.uuid() + "_" + filename; //校验文件的扩展名 if(!filename.toLowerCase().endsWith(".jpg")){ //将大写转换成小写进行比较 error("上传的图片扩展名必须是JPG", request, response); return; } //校验图片的尺寸 //保存上传的图片,把图片new成图片对象: Image,Icon,ImageIcon,BufferedImage,ImageIO /* *保存图片: *1.获取真实路径 */ String savepath = this.getServletContext().getRealPath("/book_img"); /* * 2.创建目标文件 */ File destFile = new File(savepath,filename); /* * 3.保存文件 */ try { fileItem.write(destFile);//它会把临时文件重定向到指定的路径,再删除临时文件 } catch (Exception e) { throw new RuntimeException(e); } //校验尺寸 //1.使用文件路径创建ImageIcon ImageIcon icon = new ImageIcon(destFile.getAbsolutePath()); //2.通过ImageIcon得到Image对象 Image image = icon.getImage(); //3.获取宽高来进行校验 if(image.getWidth(null)>350 || image.getHeight(null)>350){ error("您上传的图片尺寸超出了350*350像素!", request, response); destFile.delete(); //删除图片 return; } //把图片的路径设置给book对象 book.setImage_w("book_img/" + filename); //获取文件名 fileItem = fileItemList.get(2); //获取小图 filename = fileItem.getName(); //截取文件名,因为部分浏览器上传的是绝对路径 index = filename.lastIndexOf("\\"); if(index !=-1){ filename = filename.substring(index + 1); } //给文件名添加uuid的前缀,避免文件重名现象 filename = CommonUtils.uuid() + "_" + filename; //校验文件的扩展名 if(!filename.toLowerCase().endsWith(".jpg")){ error("上传的图片扩展名必须是JPG", request, response); return; } //校验图片的尺寸 //保存上传的图片,把图片new成图片对象: Image,Icon,ImageIcon,BufferedImage,ImageIO /* *保存图片: *1.获取真实路径 */ savepath = this.getServletContext().getRealPath("/book_img"); /* * 2.创建目标文件 */ destFile = new File(savepath,filename); /* * 3.保存文件 */ try { fileItem.write(destFile);//它会把临时文件重定向到指定的路径,再删除临时文件 } catch (Exception e) { throw new RuntimeException(e); } //校验尺寸 //1.使用文件路径创建ImageIcon icon = new ImageIcon(destFile.getAbsolutePath()); //2.通过ImageIcon得到Image对象 image = icon.getImage(); //3.获取宽高来进行校验 if(image.getWidth(null)>350 || image.getHeight(null)>350){ error("您上传的图片尺寸超出了350*350像素!", request, response); destFile.delete(); //删除图片 return; } //把图片的路径设置给book对象 book.setImage_b("book_img/" + filename); //调用service完成保存 book.setBid(CommonUtils.uuid()); BookService bookService = new BookService(); bookService.add(book); //保存成功信息转发到msg.jsp request.setAttribute("msg", "添加图书成功!"); request.getRequestDispatcher("/adminjsps/msg.jsp").forward(request, response); } /* * 保存错误信息,转发到add.jsp */ private void error(String msg, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("msg", msg); request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response); } }
下面是bookservice的添加方法.
public class BookService { private BookDao bookDao = new BookDao(); /** * 添加图书 * @param book */ public void add(Book book){ try { bookDao.add(book); } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } } }
下面是bookDao的sql代码.
public class BookDao { private QueryRunner qr = new TxQueryRunner(); /** * 添加图书 * @param book * @throws SQLException */ public void add(Book book) throws SQLException { String sql = "insert into t_book(bid,bname,author,price,currPrice,"+ "discount,press,publishtime,edition,pageNum,wordNum,printtime,"+ "booksize,paper,cid,image_w,image_b)"+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; Object[] params = {book.getBid(),book.getBname(),book.getAuthor(), book.getPrice(),book.getCurrPrice(),book.getDiscount(), book.getPress(),book.getPublishtime(),book.getEdition(), book.getPageNum(),book.getWordNum(),book.getPrinttime(), book.getBooksize(),book.getPaper(),book.getCategory().getCid(), book.getImage_w(),book.getImage_b()}; qr.update(sql,params); } }