首页 > 代码库 > 文件的上传Commons FileUpload(web基础学习笔记十六)

文件的上传Commons FileUpload(web基础学习笔记十六)

一、表单设置

<form action="<%=request.getContextPath()%>/jsp/admin/doAdd.jsp" enctype="multipart/form-data" method="post"></form>

设置属性:

enctype="multipart/form-data";

<tr><td class="text_tabledetail2">上传图片 </td><td><input type="file" name="picPath" value=""/></td></tr>

类型设置:type="file";

表单

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><%@ page language="java" import="java.util.*,com.pb.news.entity.*" pageEncoding="UTF-8"%><html>    <head>        <link href="<%=request.getContextPath() %>/css/common.css" rel="stylesheet" type="text/css" />        <script type="text/javascript" src="<%=request.getContextPath() %>/ckeditor/ckeditor.js"></script>    </head><body><form name ="dataForm" id="dataForm" action="<%=request.getContextPath()%>/jsp/admin/doAdd.jsp" method="post"  enctype="multipart/form-data">    <table class="tb" border="0" cellspacing="5" cellpadding="0">        <thead>            <tr><td align="center" colspan="2" class="text_tabledetail2">增加新闻</td></tr>        </thead>        <tbody>            <tr>                <td class="text_tabledetail2">分类</td>                <td>                <!-- 列出所有的新闻分类 -->                    <select name="categoryId">                        <option value="1">国内</option>                        <option value="2">国际</option>                        <option value="3">娱乐</option>                        <option value="4">军事</option>                        <option value="5">财经</option>                        <option value="6">天气</option>                    </select>                </td>            </tr>            <tr>                <td class="text_tabledetail2">标题</td>                <td><input type="text" name="title" value=""/></td>            </tr>            <tr>                <td class="text_tabledetail2">作者</td>                <td><input type="text" name="author" value=""/></td>            </tr>                        <tr>                <td class="text_tabledetail2">摘要</td>                <td><textarea id="summary" name="summary" rows="8" cols="50"></textarea></td>            </tr>            <tr>                <td class="text_tabledetail2">内容</td>                <td>                <div id="xToolbar"></div>                <textarea id="newscontent" name="newscontent" class="ckeditor" rows="8"></textarea>                </td>            </tr>            <tr>                <td class="text_tabledetail2">上传图片 </td>                <td><input type="file" name="picPath" value=""/></td>            </tr>            <tr>                <td style="text-align:center;" colspan="2">                    <button type="submit" class="page-btn" name="save">保存</button>                    <input type="hidden" name="id" value=""/>                    <button type="button" class="page-btn" name="return" onclick="javascript:location.href=http://www.mamicode.com/‘newsDetailList.jsp‘">返回</button>                </td>            </tr>        </tbody>    </table></form></body></html>

二、下载控件导入

http://commons.apache.org/

采用apache的开源工具common-fileupload这个文件上传组件,

Commons FileUpload:http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi

common-fileupload是依赖于common-io这个包的,所以还需要下载这个包。

Download Commons IO:http://commons.apache.org/proper/commons-io/download_io.cgi

下载以上2个控件并导入

三、提交页面

doAdd.jsp

<%@page import="java.io.File"%><%@page import="org.apache.commons.fileupload.FileItem"%><%@page import="java.util.List"%><%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%><%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%><%@page import="java.util.Date"%><%@page import="com.pb.news.entity.News"%><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@include file="../common/common.jsp"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>    <%        //设置页面编码     request.setCharacterEncoding("utf-8");    boolean bRet = false;    boolean bUpload = false;    String uploadFileName = "";    String fieldName = "";    //声明News对象    News news=new News();    //设置创建时间    news.setCreateDate(new Date());    //判断表单个是否有多个部分组成,将整个请求做做为判断    boolean isMultipart=ServletFileUpload.isMultipartContent(request);    //得到上传文件的保存目录,    //String uploadpath=this.getServletContext().getRealPath("/upload/");    String uploadFilePath=request.getSession().getServletContext().getRealPath("/upload/");    //判断是表单是否为多部分组成    if(isMultipart==true){        //使用Apache文件上传组件处理文件上传步骤:        //1、创建一个DiskFileItemFactory工厂        DiskFileItemFactory factory=new DiskFileItemFactory();        //2、创建一个文件上传解析器        ServletFileUpload upload=new ServletFileUpload(factory);        try{    //3、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项        List<FileItem> items=upload.parseRequest(request);         //遍历集合         for(FileItem item:items){            //如果是普通的数据            if(item.isFormField()){              //得到集合元素              fieldName=item.getFieldName();              //判断              if(fieldName.equals("title")){                  //如果是标题,就设置新闻标题,并将字符集设置为utf-8                  news.setTitle(item.getString("utf-8"));                  //如果是ID则              }else if(fieldName.equals("id")){                   //获取ID            String id = item.getString();                   //判断ID是还为空            if (id != null && !id.equals("")){                news.setId(Integer.parseInt(id));            }                   //类别,强制类型转换        }else if (fieldName.equals("categoryId")){            news.setCategoryId(Integer.parseInt(item.getString()));            //如果是摘要,设置字符编码        }else if (fieldName.equals("summary")){            news.setSummary(item.getString("UTF-8"));            //如果是内容,设置字符编码        }else if (fieldName.equals("newscontent")){            news.setContent(item.getString("UTF-8"));            //如果是作者名称,设置字符编码        }else if(fieldName.equals("author")){            news.setAuthor(item.getString("UTF-8"));        }                //如果是上传数据            }else{                //得到集合元素                String fileName = item.getName();                //判断是否为空                if(fileName!=null&&!fileName.equals("")){                    //不是空得到文件名                    File fullFile=new File(item.getName());                    //保存路径 和名字                    File saveFile = new File(uploadFilePath, fullFile.getName());                    //写入文件                    item.write(saveFile);                    //上传的文件名                    uploadFileName = fullFile.getName();                    //设置新闻图片牟路径和名字                    news.setPicPath(uploadFileName);                    //上传成功                    bUpload = true;                                }                            }         }                    }catch(Exception e){            e.printStackTrace();        }    }    System.out.println("上传成功后的文件名是::"+news.getPicPath());    //调用后台方法,将新闻信息插入数据库    bRet=newsService.addNews(news);    %>    <%    //判断是还上传成功if (bRet) {    //成功就跳转到列表页面    response.sendRedirect("newsDetailList.jsp");} else {    //返回添加的页面    response.sendRedirect("newsDetailCreate.jsp");}%></body></html>

 

文件的上传Commons FileUpload(web基础学习笔记十六)