案例37-後臺商品添加的代碼實現加入圖片上傳
阿新 • • 發佈:2018-02-22
back 獲取文件 print req and 瀏覽器 完全 dom lin
1 add.jsp代碼修改
<%@ page language="java" pageEncoding="UTF-8"%> <HTML> <HEAD> <meta http-equiv="Content-Language" content="zh-cn"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <LINK href="${pageContext.request.contextPath}/css/Style1.css"type="text/css" rel="stylesheet"> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(function(){ //頁面加載完畢後異步獲得分類數據 $.post("${pageContext.request.contextPath }/admin?method=findAllCategory", function(data){ //[{"cid":"xxx","cname":"xxx"},{},{}] //拼接多個<option value=""></option> var content=""; for(var i=0;i<data.length;i++){ content += "<option value=‘"+data[i].cid+"‘>"+data[i].cname+"</option>"; } $("#cid").html(content); }, "json" ); }); </script> </HEAD> <body> <!-- --> <form id="userAction_save_do" name="Form1" action="${pageContext.request.contextPath}/adminProduct" method="post" enctype="multipart/form-data"> <!-- <input type="hidden" name="method" value="saveProduct" > --> <table cellSpacing="1" cellPadding="5" width="100%" align="center" bgColor="#eeeeee" style="border: 1px solid #8ba7e3" border="0"> <tr> <td class="ta_01" align="center" bgColor="#afd1f3" colSpan="4" height="26"> <strong><STRONG>添加商品</STRONG> </strong> </td> </tr> <tr> <td width="18%" align="center" bgColor="#f5fafe" class="ta_01"> 商品名稱: </td> <td class="ta_01" bgColor="#ffffff"> <input type="text" name="pname" value="" id="userAction_save_do_logonName" class="bg"/> </td> <td width="18%" align="center" bgColor="#f5fafe" class="ta_01"> 是否熱門: </td> <td class="ta_01" bgColor="#ffffff"> <select name="is_hot"> <option value="1">是</option> <option value="0">否</option> </select> </td> </tr> <tr> <td width="18%" align="center" bgColor="#f5fafe" class="ta_01"> 市場價格: </td> <td class="ta_01" bgColor="#ffffff"> <input type="text" name="market_price" value="" id="userAction_save_do_logonName" class="bg"/> </td> <td width="18%" align="center" bgColor="#f5fafe" class="ta_01"> 商城價格: </td> <td class="ta_01" bgColor="#ffffff"> <input type="text" name="shop_price" value="" id="userAction_save_do_logonName" class="bg"/> </td> </tr> <tr> <td width="18%" align="center" bgColor="#f5fafe" class="ta_01"> 商品圖片: </td> <td class="ta_01" bgColor="#ffffff" colspan="3"> <input type="file" name="upload" /> </td> </tr> <tr> <td width="18%" align="center" bgColor="#f5fafe" class="ta_01"> 所屬分類: </td> <td class="ta_01" bgColor="#ffffff" colspan="3"> <select id="cid" name="cid"> </select> </td> </tr> <tr> <td width="18%" align="center" bgColor="#f5fafe" class="ta_01"> 商品描述: </td> <td class="ta_01" bgColor="#ffffff" colspan="3"> <textarea name="pdesc" rows="5" cols="30"></textarea> </td> </tr> <tr> <td class="ta_01" style="WIDTH: 100%" align="center" bgColor="#f5fafe" colSpan="4"> <button type="submit" id="userAction_save_do_submit" value="確定" class="button_ok"> 确定 </button> <FONT face="宋體"> </FONT> <button type="reset" value="重置" class="button_cancel">重置</button> <FONT face="宋體"> </FONT> <INPUT class="button_ok" type="button" onclick="history.go(-1)" value="返回"/> <span id="Label1"></span> </td> </tr> </table> </form> </body> </HTML>
2 AdminProductServlet代碼
package www.test.web.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; 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 org.apache.commons.beanutils.BeanUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.IOUtils; import www.test.domain.Category; import www.test.domain.Product; import www.test.service.AdminService; import www.test.utils.CommonsUtils; public class AdminProductServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //目的:收集表單的數據封裝一個Product實體 將上傳圖片存儲到服務器磁盤上 Product product = new Product(); //收集數據的容器 Map<String,Object> map = new HashMap<String,Object>(); try { //接收文件上傳 // 1 創建磁盤文件項工廠 String path_temp = this.getServletContext().getRealPath("temp"); DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024,new File(path_temp)); // 2 創建文件上傳核心類 ServletFileUpload upload = new ServletFileUpload(factory); //設置上傳文件的名稱的編碼 upload.setHeaderEncoding("UTF-8"); //ServletFileUpload的API boolean multipartContent = upload.isMultipartContent(request); //判斷表單是不是文件上傳的表單 if(multipartContent){ //是文件上傳表單 // 3 ******解析request---- 獲得文件項集合 List<FileItem> parseRequest = upload.parseRequest(request); if(parseRequest!=null){ // 4 遍歷文件項集合 for (FileItem fileItem : parseRequest) { // 5 判斷是普通表單項/文件上傳項 boolean formField = fileItem.isFormField(); if(formField){ //普通表單項 username = zhangsan String fieldName = fileItem.getFieldName(); String fieldValue = fileItem.getString("UTF-8");//對普通表單項的內容進行編碼 //一個一個的存入到容器中 鍵值對 存儲完成之後使用BeanUtils進行封裝。 map.put(fieldName, fieldValue); // 註意:當表單是enctype="multipart/form-data"時 request.getParameter相關的方法都失效 //String parameter = request.getParameter("username");獲取不到數據 }else{ // 文件上傳項 String fileName = fileItem.getName();//獲取文件名 //不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交的文件名是帶有路徑的, //如:c:\nihao\a.txt,而有些只是單純的文件名,如:a.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 fileName = fileName.substring(fileName.lastIndexOf("\\")+1); //獲得上傳文件的內容 也是就獲得與文件關聯的輸入流 InputStream in = fileItem.getInputStream(); //獲取存儲文件的絕對地址 String path_store = this.getServletContext().getRealPath("upload"); OutputStream out = new FileOutputStream(path_store+"/"+fileName); //D:/xxx/xxx/xx/xxx.jpg //上傳文件實際上就是復制文件到服務器 直接使用工具類 IOUtils.copy(in, out); //關閉資源 in.close(); out.close(); //刪除臨時文件 fileItem.delete(); //將圖片的相對地址存儲到map容器中,這樣就可以直接使用BeanUtils封裝到裏面去了 map.put("pimage", "upload/"+fileName); } } } //封裝 BeanUtils.populate(product, map); //是否product對象封裝數據完全,不完全的手動封裝 //private String pid product.setPid(CommonsUtils.getUUID()); // private Date pdate; product.setPdate(new Date()); // private int pflag; product.setPflag(0); //private Category category; Category category = new Category(); category.setCid(map.get("cid").toString()); product.setCategory(category); //將封好的product傳遞給service層 AdminService service = new AdminService(); service.saveProduct(product); }else{ //不是文件上傳表單 //使用原始的表單數據的獲取方式 } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
3 AdminService代碼
// 添加商品 public void saveProduct(Product product) throws SQLException { AdminDao dao = new AdminDao(); dao.saveProduct(product); }
4 AdminDao代碼
//添加商品 public void saveProduct(Product product) throws SQLException { QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource()); String sql = "insert into product values (?,?,?,?,?,?,?,?,?,?)"; qr.update(sql, product.getPid(),product.getPname(),product.getMarket_price(), product.getShop_price(),product.getPimage(),product.getPdate(), product.getIs_hot(),product.getPdesc(),product.getPflag(), product.getCategory().getCid()); }
案例37-後臺商品添加的代碼實現加入圖片上傳