案例37-后台商品添加的代码实现加入图片上传

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">
            &nbsp;
            <!-- <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">
                            &#30830;&#23450;
                        </button>

                        <FONT face="宋体">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</FONT>
                        <button type="reset" value="重置" class="button_cancel">&#37325;&#32622;</button>

                        <FONT face="宋体">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</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());
}

 

posted @ 2018-02-22 08:53  Jepson6669  阅读(1343)  评论(0编辑  收藏  举报