Jsp+Servlet實現檔案上傳下載(一)--檔案上傳

indexman發表於2017-12-28

檔案上傳和下載功能是Java Web必備技能,很實用。

本文使用的是Apache下的著名的檔案上傳元件

org.apache.commons.fileupload 實現

下面結合最近看到的一些資料以及自己的嘗試,先寫第一篇檔案上傳後續會逐步實現下載,展示檔案列表,上傳資訊持久化等。


廢話少說,直接上程式碼

第一步,引用jar包,設定上傳目錄

commons-fileupload-1.3.1.jar
commons-io-2.4.jar


上傳目錄:WEB-INF/tempFiles和WEB-INF/uploadFiles


第二步,編寫JSP頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>檔案上傳測試</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="<%=request.getContextPath()%>/UploadServlet">
    檔案: <input type="file" name="upfile"><br/>
    <br/>
    <input type="submit" value="上傳">
</form>
<c:if test="${not empty errorMessage}">
    <input type="text" id="errorMessage" value="${errorMessage}" style="color:red;" disabled="disabled">
</c:if>
</body>
</html>


第三步,編寫Servlet,處理檔案上傳的核心

package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * 處理檔案上傳
 *
 * @author xusucheng
 * @create 2017-12-27
 **/
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設定檔案上傳基本路徑
        String savePath = this.getServletContext().getRealPath("/WEB-INF/uploadFiles");
        //設定臨時檔案路徑
        String tempPath = this.getServletContext().getRealPath("/WEB-INF/tempFiles");
        File tempFile = new File(tempPath);
        if (!tempFile.exists()) {
            tempFile.mkdir();
        }

        //定義異常訊息
        String errorMessage = "";
        //建立file items工廠
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //設定緩衝區大小
        factory.setSizeThreshold(1024 * 100);
        //設定臨時檔案路徑
        factory.setRepository(tempFile);
        //建立檔案上傳處理器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //監聽檔案上傳進度
        ProgressListener progressListener = new ProgressListener() {
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("正在讀取檔案: " + pItems);
                if (pContentLength == -1) {
                    System.out.println("已讀取: " + pBytesRead + " 剩餘0");
                } else {
                    System.out.println("檔案總大小:" + pContentLength + " 已讀取:" + pBytesRead);
                }
            }
        };
        upload.setProgressListener(progressListener);

        //解決上傳檔名的中文亂碼
        upload.setHeaderEncoding("UTF-8");
        //判斷提交上來的資料是否是上傳表單的資料
        if (!ServletFileUpload.isMultipartContent(request)) {
            //按照傳統方式獲取資料
            return;
        }

        //設定上傳單個檔案的大小的最大值,目前是設定為1024*1024位元組,也就是1MB
        upload.setFileSizeMax(1024 * 1024);
        //設定上傳檔案總量的最大值,最大值=同時上傳的多個檔案的大小的最大值的和,目前設定為10MB
        upload.setSizeMax(1024 * 1024 * 10);

        try {
            //使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = iterator.next();

                //判斷jsp提交過來的是不是檔案
                if (item.isFormField()) {
                    errorMessage = "請提交檔案!";
                    break;
                } else {
                    //檔名
                    String fileName = item.getName();
                    if (fileName == null || fileName.trim() == "") {
                        System.out.println("檔名為空!");
                    }
                    //處理不同瀏覽器提交的檔名帶路徑問題
                    fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                    //副檔名
                    String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
                    //判斷副檔名是否合法
                    if (!validExtension(fileExtension)) {
                        errorMessage = "上傳檔案非法!";
                        item.delete();
                        break;
                    }
                    //獲得檔案輸入流
                    InputStream in = item.getInputStream();
                    //得到儲存檔案的名稱
                    String saveFileName = createFileName(fileName);
                    //得到檔案儲存路徑
                    String realFilePath = createRealFilePath(savePath, saveFileName);
                    //建立檔案輸出流
                    FileOutputStream out = new FileOutputStream(realFilePath);
                    //建立緩衝區
                    byte buffer[] = new byte[1024];
                    int len = 0;
                    while ((len = in.read(buffer)) > 0) {
                        //寫檔案
                        out.write(buffer, 0, len);
                    }
                    //關閉輸入流
                    in.close();
                    //關閉輸出流
                    out.close();
                    //刪除臨時檔案 TODO
                    item.delete();
                    //將上傳檔案資訊儲存到附件表中 TODO
                }

            }

        } catch (FileUploadBase.FileSizeLimitExceededException e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "單個檔案超出最大值!!!");
            request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response);
            return;
        } catch (FileUploadBase.SizeLimitExceededException e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "上傳檔案的總的大小超出限制的最大值!!!");
            request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response);
            return;
        } catch (FileUploadException e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "檔案上傳失敗!!!");
            request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response);
            return;
        }

        request.setAttribute("errorMessage", errorMessage);
        request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response);


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    private boolean validExtension(String fileExtension) {
        String[] exts = {"jpg", "txt", "doc", "pdf"};
        for (int i = 0; i < exts.length; i++) {
            if (fileExtension.equals(exts[i])) {
                return true;
            }

        }

        return false;
    }

    private String createFileName(String fileName) {
        return UUID.randomUUID().toString() + "_" + fileName;
    }

    /**
     * 根據基本路徑和檔名稱生成真實檔案路徑,基本路徑\\年\\月\\fileName
     *
     * @param basePath
     * @param fileName
     * @return
     */
    private String createRealFilePath(String basePath, String fileName) {
        Calendar today = Calendar.getInstance();
        String year = String.valueOf(today.get(Calendar.YEAR));
        String month = String.valueOf(today.get(Calendar.MONTH) + 1);


        String upPath = basePath + File.separator + year + File.separator + month + File.separator;
        File uploadFolder = new File(upPath);
        if (!uploadFolder.exists()) {
            uploadFolder.mkdirs();
        }

        String realFilePath = upPath + fileName;

        return realFilePath;
    }
}



第四步,測試

以本機為例,展示幾張截圖:

http://localhost:8080/helloweb/pages/upload/upload.jsp


















相關文章