文件(图片)资源上传到Javaweb项目中

上传的原理:
①获取本地的文件或图片资源(电脑中真实存在的资源)
②使用form表单将图片上传到servlet
③servlet复制到你设置的路径中(一般都复制到你的项目中)
④然后再把图片地址存储到数据库中
具体步骤
①下载commons-fileupload-1.3.1.jar或者其他的fileupload的jar包
②给form表单添加 enctype="multipart/form-data" method="post"
这两个属性必<form id="addForm"  action="/addNewTrack.express" enctype="multipart/form-data" method="post">
            <table class="panelTable" border="0" cellspacing="0" cellpadding="0">
                <tbody>
                <tr>
                    <td>站点编号:td>
                    <td><input name="station_id" type="text" readonly="readonly" required="required" />td>
                    <td>快递单日期:td>
                    <td><input name="track_date" type="text" readonly="readonly" required="required" />td>
                tr>
                <tr>
                    <td>寄件人姓名:td>
                    <td><input name="client_name" type="text" required="required" />td>
                    <td>寄件人电话:td>
                    <td><input name="client_phone" type="text" required="required" />td>
                tr>
                <tr>
                    <td>寄件人邮件:td>
                    <td colspan="3"><input name="client_email" type="text" required="required" />td>
                tr>
                <tr>
                    <td>寄件人地址:td>
                    <td colspan="3">
                        <input name="clientAddressCountry" type="text" placeholder="国家" />
                        <input name="clientAddressProvince" type="text" placeholder="省份" required="required" />
                        <input name="clientAddressCity" type="text" placeholder="城市/直辖市" required="required" />
                        <input name="clientAddressCounty" type="text" placeholder="县/区" required="required" />
                        <input name="clientAddressTown" type="text" placeholder="镇/街道" required="required" />
                        <input name="clientAddressVillage" type="text" placeholder="村" />
                    td>
                tr>
                <tr>
                    <td>收件人姓名:td>
                    <td><input name="recipients_name" type="text" required="required" />td>
                    <td>收件人电话:td>
                    <td><input name="recipients_phone" type="text" required="required" />td>
                tr>
                <tr>
                    <td>收件人邮件:td>
                    <td colspan="3"><input name="recipients_email" type="text" required="required" />td>
                tr>
                <tr>
                    <td>收件人地址:td>
                    <td colspan="3">
                        <input name="recipientsAddressCountry" type="text" placeholder="国家" />
                        <input name="recipientsAddressProvince" type="text" placeholder="省份" required="required" />
                        <input name="recipientsAddressCity" type="text" placeholder="城市/直辖市" required="required" />
                        <input name="recipientsAddressCounty" type="text" placeholder="县/区" required="required" />
                        <input name="recipientsAddressTown" type="text" placeholder="镇/街道" required="required" />
                        <input name="recipientsAddressVillage" type="text" placeholder="村" />
                    td>
                tr>
                <tr>
                    <td>包裹名称:td>
                    <td><input name="package_content" type="text" />td>
                    <td>包裹重量:td>
                    <td><input name="package_weight" type="text" required="required" />td>
                tr>
                <tr>
                    <td>包裹是否保价:td>
                    <td>
                        <select name="package_supportValue">
                            <option value="否">option>
                            <option value="是">option>
                        select>
                    td>
                    <td>包裹价值评估:td>
                    <td>
                        <select name="package_valueDeclare">
                            <option value="不评估">不评估option>
                            <option value="100-300">100-300option>
                            <option value="300-500">300-500option>
                            <option value="其他">其他option>
                        select>
                    td>
                tr>
                <tr>
                    <td>包裹运费:td>
                    <td><input name="package_freight" type="text" required="required" />td>
                    <td colspan="2">
                        <a href="http://www.sf-express.com/cn/sc/dynamic_functions/price/" target="_blank"><input type="button" value="计算运费" />a>
                    td>
                tr>
                <tr>
                    <td>包裹备注:td>
                tr>
                <tr>
                    <td colspan="4">
                        <textarea name="package_remark" rows="5">textarea>
                    td>
                tr>
                <tr>
                    <td>包裹图片:td>
                    <td><input id="add_file_upload" name="upload" type="file" value="上传图片" accept="image/*" required="required" />td>
                    <td style="display: none"><input type="submit" value="提交文件" />td>
                tr>
                tbody>
            table>
            <div class="image_container" style="padding: 0 20px;">
                <img id="add_preview" style="height:170px;width: auto;border-width:0px;"/>
            div>
        form>
③将form表单根据web.xml的设置提交到对应servlet中


    <servlet>
        <servlet-name>expressservlet-name>
        <servlet-class>com.wzb.servlet.ExpressServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>expressservlet-name>
        <url-pattern>*.expressurl-pattern>
    servlet-mapping>

这里有一个需要注意的地方:
如果你想使用ajax提交其他普通数据,form表单只提交上传文件,并且使用js提交,那么你会发现不管表单是否首先提交,它都比ajax提交的慢,换句话说,先执行ajax的一系列操作,然后执行form表单操作。这会给你的代码造成倍的困难,而且本来只需一次向数据库插入操作,由于两次提交,至少要进行两次操做,所以结论是:你最好都是用form表单提交的形式,之后servlet中加上
response.sendRedirect(request.getContextPath()+”/page/proscenium/ticketMsgManage.jsp”);
别忘了返回当前页面
④servlet对上传文件进行业务处理
@Override
public void insertData(HttpServletRequest request, HttpServletResponse response) throws Exception {
/**
* 首先判断form的enctype是不是multipart/form-data
* 同时也判断了form的提交方式是不是post
* 方法:isMultipartContent(request)
*/
//将ajax传入的参数作为属性值传入到LoginEmployeeModel实例
//创建一个TrackTicketModel实例
TrackTicketModel trackTicketModel = new TrackTicketModel();
String package_img = null;
//保存普通表单域的参数
//获取ajax传入的值
//设置日期转化格式
SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Date track_date = null;
String client_name = null;
String client_phone = null;
String client_email = null;
String clientAddressCountry = null;
String clientAddressProvince = null;
String clientAddressCity = null;
String clientAddressCounty = null;
String clientAddressTown = null;
String clientAddressVillage = null;
String recipients_name = null;
String recipients_phone = null;
String recipients_email = null;
String recipientsAddressCountry = null;
String recipientsAddressProvince = null;
String recipientsAddressCity = null;
String recipientsAddressCounty = null;
String recipientsAddressTown = null;
String recipientsAddressVillage = null;
String package_content = null;
BigDecimal package_weight = null;
String package_supportValue = null;
String package_valueDeclare = null;
BigDecimal package_freight = null;
String package_remark = null;
if(ServletFileUpload.isMultipartContent(request)){
request.setCharacterEncoding(“utf-8”);

        // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
        DiskFileItemFactory factory =  new DiskFileItemFactory();

        //设置文件存放的临时文件夹,这个文件夹要真实存在
        File fileDir = new File("H:\\image");
        if(fileDir.isDirectory() && fileDir.exists()==false){
            fileDir.mkdir();
        }
        factory.setRepository(fileDir);

        //设置最大占用的内存
        factory.setSizeThreshold(1024000);

        //创建ServletFileUpload对象
        ServletFileUpload sfu = new ServletFileUpload(factory);
        sfu.setHeaderEncoding("utf-8");

        //设置单个文件最大值byte
        sfu.setFileSizeMax(102400000);

        //所有上传文件的总和最大值byte
        sfu.setSizeMax(204800000);

        List items =  null;

        try {
            items = sfu.parseRequest(request);
        }catch (FileUploadBase.SizeLimitExceededException e) {
            System.out.println("文件大小超过了最大值");
        } catch(FileUploadException e) {
            e.printStackTrace();
        }

        //取得items的迭代器
        Iterator iter = items==null?null:items.iterator();

        //图片上传后存放的路径目录
        File images = new File("E:/IDEA_workatation/ECMBS/web/assert/upload/images");
        if(images.exists()==false){
            images.mkdirs();
        }

        //迭代items
        while(iter!=null && iter.hasNext()){
            FileItem item = (FileItem) iter.next();
            //如果传过来的是普通的表单域
            if(item.isFormField()){
                if ("track_date".equals(item.getFieldName())){
                    track_date = format.parse(item.getString("UTF-8"));
                }
                if ("client_name".equals(item.getFieldName())){
                    client_name = item.getString("UTF-8");
                }
                if ("client_phone".equals(item.getFieldName())){
                    client_phone = item.getString("UTF-8");
                }
                if ("client_email".equals(item.getFieldName())){
                    client_email = item.getString("UTF-8");
                }
                if ("clientAddressCountry".equals(item.getFieldName())){
                    clientAddressCountry = item.getString("UTF-8");
                }
                if ("clientAddressProvince".equals(item.getFieldName())){
                    clientAddressProvince = item.getString("UTF-8");
                }
                if ("clientAddressCity".equals(item.getFieldName())){
                    clientAddressCity = item.getString("UTF-8");
                }
                if ("clientAddressCounty".equals(item.getFieldName())){
                    clientAddressCounty = item.getString("UTF-8");
                }
                if ("clientAddressTown".equals(item.getFieldName())){
                    clientAddressTown = item.getString("UTF-8");
                }
                if ("clientAddressVillage".equals(item.getFieldName())){
                    clientAddressVillage = item.getString("UTF-8");
                }
                if ("recipients_name".equals(item.getFieldName())){
                    recipients_name = item.getString("UTF-8");
                }
                if ("recipients_phone".equals(item.getFieldName())){
                    recipients_phone = item.getString("UTF-8");
                }
                if ("recipients_email".equals(item.getFieldName())){
                    recipients_email = item.getString("UTF-8");
                }
                if ("recipientsAddressCountry".equals(item.getFieldName())){
                    recipientsAddressCountry = item.getString("UTF-8");
                }
                if ("recipientsAddressProvince".equals(item.getFieldName())){
                    recipientsAddressProvince = item.getString("UTF-8");
                }
                if ("recipientsAddressCity".equals(item.getFieldName())){
                    recipientsAddressCity = item.getString("UTF-8");
                }
                if ("recipientsAddressCounty".equals(item.getFieldName())){
                    recipientsAddressCounty = item.getString("UTF-8");
                }
                if ("recipientsAddressTown".equals(item.getFieldName())){
                    recipientsAddressTown = item.getString("UTF-8");
                }
                if ("recipientsAddressVillage".equals(item.getFieldName())){
                    recipientsAddressVillage = item.getString("UTF-8");
                }
                if ("package_content".equals(item.getFieldName())){
                    package_content = item.getString("UTF-8");
                }
                if ("package_weight".equals(item.getFieldName())){
                    package_weight = BigDecimal.valueOf(Double.valueOf(item.getString("UTF-8")));
                }
                if ("package_supportValue".equals(item.getFieldName())){
                    package_supportValue = item.getString("UTF-8");
                }
                if ("package_valueDeclare".equals(item.getFieldName())){
                    package_valueDeclare = item.getString("UTF-8");
                }
                if ("package_freight".equals(item.getFieldName())){
                    package_freight = BigDecimal.valueOf(Double.valueOf(item.getString("UTF-8")));
                }
                if ("package_remark".equals(item.getFieldName())){
                    package_remark = item.getString("UTF-8");
                }
            }
            //文件域
            else if(!item.isFormField()){
                //System.out.println("源图片:" + item.getName());
                String fileName = item.getName();
                BufferedInputStream in = new BufferedInputStream(item.getInputStream());
                //文件存储在H:/upload/images/目录下,这个目录也得存在
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(images.getAbsolutePath()+"/"+fileName)));
                Streams.copy(in, out, true);
                //使用Session保存图片路径
                String url = request.getContextPath()+"/assert/upload/images/"+fileName;
                package_img = url;
                trackTicketModel.setPackage_img(package_img);
                System.out.println("url : "+url);
            }
        }
    }else {
        System.out.println("表单的enctype 类型错误");
    }
    //设置属性值
    trackTicketModel.setTrack_date(track_date);
    trackTicketModel.setClient_name(client_name);
    trackTicketModel.setClient_phone(client_phone);
    trackTicketModel.setClient_email(client_email);
    trackTicketModel.setClientAddressCountry(clientAddressCountry);
    trackTicketModel.setClientAddressProvince(clientAddressProvince);
    trackTicketModel.setClientAddressCity(clientAddressCity);
    trackTicketModel.setClientAddressCounty(clientAddressCounty);
    trackTicketModel.setClientAddressTown(clientAddressTown);
    trackTicketModel.setClientAddressVillage(clientAddressVillage);
    trackTicketModel.setRecipients_name(recipients_name);
    trackTicketModel.setRecipients_phone(recipients_phone);
    trackTicketModel.setRecipients_email(recipients_email);
    trackTicketModel.setRecipientsAddressCountry(recipientsAddressCountry);
    trackTicketModel.setRecipientsAddressProvince(recipientsAddressProvince);
    trackTicketModel.setRecipientsAddressCity(recipientsAddressCity);
    trackTicketModel.setRecipientsAddressCounty(recipientsAddressCounty);
    trackTicketModel.setRecipientsAddressTown(recipientsAddressTown);
    trackTicketModel.setRecipientsAddressVillage(recipientsAddressVillage);
    trackTicketModel.setPackage_content(package_content);
    trackTicketModel.setPackage_freight(package_freight);
    trackTicketModel.setPackage_weight(package_weight);
    trackTicketModel.setPackage_remark(package_remark);
    trackTicketModel.setPackage_supportValue(package_supportValue);
    trackTicketModel.setPackage_valueDeclare(package_valueDeclare);
    trackTicketModel.setEmployee_id(loginEmployee.getEmployee_id());
    trackTicketModel.setStationAddressUniqueId(GetUUIDUtil.getId());
    trackTicketModel.setEmployeeAddressUniqueId(GetUUIDUtil.getId());
    trackTicketModel.setClientAddressUniqueId(GetUUIDUtil.getId());
    trackTicketModel.setRecipientsAddressUniqueId(GetUUIDUtil.getId());
    trackTicketModel.setClient_uiqueId(GetUUIDUtil.getId());
    trackTicketModel.setRecipients_uiqueId(GetUUIDUtil.getId());
    trackTicketModel.setPackage_uiqueId(GetUUIDUtil.getId());
    //创建LoginImpl实例
    ExpressImpl expressImpl = new ExpressImpl();
    expressImpl.trackTicketModel1 = trackTicketModel;
    //调用LoginImpl实例的方法向数据库插入新的登录用户
    int returnValue = expressImpl.insertTrack(new HashMap());
    //创建一个输出流对象
    PrintWriter out = response.getWriter();
    //定义一个判断插入是否成功的变量
    boolean flag = false;
    //如果returnValue等于1,表示插入成功,否则失败
    if(returnValue == 1){
        flag = true;
    }
    //向前台发送信息
    try {
        //out.print(String.valueOf(flag));
        response.sendRedirect(request.getContextPath()+"/page/proscenium/ticketMsgManage.jsp");
    }catch (Exception e){
        System.out.println("Error Location : "+"ExpressServlet"+"."+"insertData");
        System.out.println("Error Case : "+"新增快递单信息"+"失败");
        e.printStackTrace();
    }finally {
        //提交数据库操作和关闭数据库会话
        expressImpl.commitAndCloseSqlSession();
        //刷新输出流
        out.flush();
        //关闭输出流
        out.close();
    }
}

⑤查看你的项目运行的结果,文件上传基本上好使了
另外,你存储到数据库中的是文件或者图片的地址,而不是直接将图片或文件存储进去,这么做的原因是:
首先对数据库的读/写的速度永远都赶不上文件系统处理的速度
其次数据库备份变的巨大,越来越耗时间,最后对文件的访问需要穿越你的应用层和数据库层
图片是数据库最大的杀手
还是使用varchar存放一个url然后在调用吧!
反正图片,文件,二进制数这三样东西永远别存数据库。

你可能感兴趣的:(程序员笔记)