文件的上傳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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM