圖片上傳格式以及尺寸大小的限制
阿新 • • 發佈:2019-02-17
首先需要上傳圖片的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);
}
}