记一种有图片上传的表单提交
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>动态加载下拉框中的类别_文件上传_添加商品</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script> </head> <body> <!-- 上传对客户端和服务器都有要求 --> <!-- 客户端: 1_提交方式为POST,即method="POST" 2_为每个表单项取一个名字,即<input name="pname"> 3_ enctype="application/x-www-form-urlencoded"表示将表单中的内容按URL编码后,随着请求传递到服务器,强调要编码 application/x-www-form-urlencoded是一个默认值 enctype="multipart/form-data"表示将表单中的内容原封不动的将数据随着请求传递到服务器,强调不编码 注意,是对整个表单,只要表单中有上传文件,就得用multipart/form-data,否则就用application/x-www-form-urlencoded --> <form action="${pageContext.request.contextPath}/ProductServlet?action=add" method="POST" enctype="multipart/form-data"> <table border="2" align="center"> <tr> <th>名称[FileItem]</th> <td><input type="text" name="pname" value="小米cc手机"/></td> <th>市场价[FileItem]</th> <td><input type="text" name="market_price" value="105"/></td> <th>商场价[FileItem]</th> <td><input type="text" name="shop_price" value="100"/></td> </tr> <tr> <th>上传文件[FileItem]</th> <td><input type="file" name="pimage"/></td> <th>是否热门[FileItem]</th> <td> <select name="is_hot" style="111px"> <option value="1">热门</option> <option value="0">冷门</option> </select> </td> <th>是否上架[FileItem]</th> <td> <select name="pflag" style="111px"> <option value="1">上架</option> <option value="0">下架</option> </select> </td> </tr> <tr> <th>所属类别[FileItem]</th> <td> <select id="category" name="cid" style="222px"> </select> </td> </tr> <tr> <th>描述[FileItem]</th> <td colspan="6"> <textarea style="777px" name="pdesc" cols="30" rows="3">小米小米我爱你,就像老鼠爱大米</textarea> </td> </tr> <tr> <td colspan="8" align="center"> <input type="submit" value="提交" style="222px"/> </td> </tr> </table> </form> <!-- 浏览器加载jsp页面时,向服务器发送AJAX请求,获取所有类别信息,并动态的添加到下拉框中 --> <script type="text/javascript"> $(function(){ var url = "${pageContext.request.contextPath}/CategoryServlet?action=findAllCategory"; var data = null; var callback = function(backData){ //解析JSON对象 for(var i=0;i<backData.length;i++){ //一个Eclipse插件,它的名字是:JSEclipse插件 var cid = backData[i].cid; var cname = backData[i].cname; //创建option标签 var $option = $("<option value='"+cid+"'>"+cname+"</option>"); //将option标签动态添加select下拉列表框中 $("#category").append($option); }//for end }; var type = "json"; $.post(url,data,callback,type); }); </script> </body> </html>
后台代码
private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ try { //创建Map<String,Object>对象,收集普通字段和上传文字字段的内容 Map<String,Object> map=new HashMap<String,Object>(); //创建类别和商品对象 Category category=new Category(); Product product= new Product(); //创建上传文件工厂对象(辅助) DiskFileItemFactory factory=new DiskFileItemFactory(); //创建上传文件对象(核心) ServletFileUpload upload=new ServletFileUpload(factory); //用上传文件对象去解析请求中的所有表单数据,每个表单项都是FileItem类型 //FileItem类型既表示普通字段,也表示上传文件字段 List<FileItem> list=upload.parseRequest(request); for (FileItem fileItem : list) { //如果是普通字段 if(fileItem.isFormField()){ //普通字段的名,即<input name="pname"> String name=fileItem.getFieldName(); //普通字段的值,即<input value="小米cc手机">,填写的数据 String value=fileItem.getString("UTF-8"); //收集普通字段的名和值 map.put(name,value); //如果是上传文件字段的话(1) }else{ //获取上传文件的名,即:<input name="pimage"/> String name=fileItem.getFieldName(); //获取上传文件名:即:<input value="a.jpg"/>,getName()用于上传文件字段 String value=fileItem.getName(); //收集上传字段的名和值 map.put(name,"products/1/"+value); //将a.jpg保存到服务器指定的目录下,获取上传文件的输入流 InputStream is=fileItem.getInputStream(); String path=this.getServletContext().getRealPath("/products/1/"+value); OutputStream os=new FileOutputStream(path); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } //将Map集合封装到Category,Product BeanUtils.populate(category, map); BeanUtils.populate(product, map); //封装上架时间 product.setPdate(new Date()); //封装类别 product.setCategory(category); //创建业务层对象,并调用业务方法 ProductService service = new ProductService(); int i = service.add(product); if(i<=0){ int a=100/0; } request.setAttribute("MESSAGE","添加商品成功"); request.getRequestDispatcher("/WEB-INF/message.jsp").forward(request,response); } catch (Exception e) { e.printStackTrace(); request.setAttribute("MESSAGE","添加商品失败"); request.getRequestDispatcher("/WEB-INF/message.jsp").forward(request,response); } }