Fork me on GitHub

文件的上传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='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>

 四、设置文件大小和类型

4.1、html页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
<!-- 声明表单属性为enctype=multipart/form-data -->
<form action="doupload.jsp" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>上传者</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<!-- 设置类型为file -->
<td colspan="2"><input type="file" name="filename"/></td>
</tr>
<tr>
<td><input type="submit" value="提交" /></td>
</tr>
</table>
</form>
<%
//判断请求是还为空
Object name=request.getAttribute("name");
if(name!=null){
    out.println(name.toString()+"<br/>");
}
//判断请求是还为空
Object msg=request.getAttribute("msg");
if(msg!=null){
    out.println(msg.toString()+"<br/>");
}
//判断请求是还为空
Object imgsrc=request.getAttribute("imgsrc");
if(imgsrc!=null){
    out.println(imgsrc.toString()+"<br/>");
    out.println("<img src='"+imgsrc.toString()+"'/>");
}

%>


</body>
</html>

4.2 、JSP页面

<%@page import="java.io.File"%>
<%@page import="java.util.Date"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.ArrayList"%>
<%@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.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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 isMutipart=ServletFileUpload.isMultipartContent(request);
//设置允许上传的文件格式
List<String> filelist=new ArrayList<String>();
filelist.add(".jpg");
filelist.add(".png");
filelist.add(".gif");
if(isMutipart==true){
    //创建磁盘工厂类
    FileItemFactory factory=new DiskFileItemFactory();
    //创建上传文件解析器
    ServletFileUpload upload=new ServletFileUpload(factory);
    //将整个请求做为一个集合
    List<FileItem> items=upload.parseRequest(request);
    //遍历
    for(FileItem item:items){
        if(item.isFormField()){
            //如果是普通表单按普通表单处理
            //String username=item.getFieldName();
            String name=item.getString("utf-8");
            request.setAttribute("name", name);
            
        }else{
            //如果是上传文件
            //获取文件名称
            String filename=item.getName();
            //获取文件扩展名
            String fileext=filename.substring(filename.lastIndexOf("."));
            //判断扩展名
            if(filelist.contains(fileext)){
                //判断文件大小小于1M可以上传
                if(item.getSize()<1024*1024){
                    //获取文件上传路径
                    String uploadpath=this.getServletContext().getRealPath("upload");
                    //对文件重命名
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss");
                    //当前时间加扩展名
                    String newfilename=sdf.format(new Date())+fileext;
                    //文件对象
                    File savefile=new File(uploadpath,newfilename);
                    //开始上传
                    item.write(savefile);
                    request.setAttribute("msg", "上传成功");
                    request.setAttribute("imgsrc", "../upload/"+newfilename);
                }else{
                    //判断文件大小大于512K可以上传
                    //提示错误类型
                request.setAttribute("msg","文件只能上传1M以下的 !");
                }
            }else{
                //提示错误类型
                request.setAttribute("msg", "只能上传jpb,png,gif的图片");
            }
        }
        
    }
    //转发到上传页面
    request.getRequestDispatcher("uploadtest.jsp").forward(request, response);
}

%>

</body>
</html>

 

posted @ 2015-01-30 02:51  森林森  阅读(4058)  评论(3编辑  收藏  举报