天天看點

檔案上傳

檔案上傳Java實作

檔案上傳

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
  version="5.0">
</web-app>
           
<dependencies>
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
    
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>
  </dependencies>

           

注意事項

  1. 上傳檔案需要放在外界無法直接通路的目錄,例如

    WEB-INF

    目錄;
  2. 上傳檔案的檔案名一定要保持唯一性; -時間戳 -

    uuid

    -
  3. 限制檔案上傳的最大值
  4. 可以限制上傳檔案的類型,在收到上傳檔案時,判斷字尾名是否合法;
package com.jezer.servlet;

import org.apache.commons.fileupload.FileItem;
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.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.List;
import java.util.UUID;

/**
 * @author Jay_Soul
 */
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //判斷上傳的檔案是普通表單還是帶檔案的表單
        if (!ServletFileUpload.isMultipartContent(req)){
            return; //終止方法運作,說明這是一個普通的表單,直接傳回
        }
        //上傳檔案需要放在外界無法直接通路的目錄,例如WEB-INF目錄;
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()){
            boolean mkdir = uploadFile.mkdir();//建立目錄
            System.out.println(mkdir);
        }
        //緩存,臨時檔案
        //臨時路徑,假如檔案超過了預期的大小,我們就把它放到一個臨時檔案,過幾天自動删除,或者提醒使用者轉存為永久
        String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
        File tempFile = new File(tempPath);
        if (!tempFile.exists()){
            tempFile.mkdir();//建立目錄
        }
        // 處理上傳的檔案,一般都需要通過流來擷取,我們可以使用 request.getInputstream(),原生态的檔案上傳流擷取,十分麻煩
        // 但是我們都建議使用 Apache的檔案上傳元件來實作, common-fileupload,它需要依賴于commons-io元件;

        try {
            //1. 建立DiskFileItemFactory對象,處理檔案路徑或者大小限制
            /*
             * 通過這個工廠設定一個緩沖區,當上傳的檔案大于這個緩沖區的時候,将他放到臨時檔案 factory.setSizeThreshold(1024 * 1024);
             * 緩存區大小為1M factory.setRepository (file);
             * 臨時目錄的儲存目錄,需要一個File
             */
            DiskFileItemFactory factory = getDiskFileItemFactory(tempFile);
            // 2、擷取ServletFileUpload
            ServletFileUpload upload = getServletFileUpload(factory);

            // 3、處理上傳檔案
            // 把前端請求解析,封裝成FileItem對象,需要從ServletFileUpload對象中擷取
            String msg = uploadParseRequest(upload, req, uploadPath);
            // Servlet請求轉發消息
            System.out.println(msg);
            if("檔案上傳成功!".equals(msg)) {
                // Servlet請求轉發消息
                req.setAttribute("msg",msg);
                req.getRequestDispatcher("info.jsp").forward(req, resp);
            }else {
                msg ="請上傳檔案";
                req.setAttribute("msg",msg);
                req.getRequestDispatcher("info.jsp").forward(req, resp);
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        }

    }
    public static DiskFileItemFactory getDiskFileItemFactory(File tempFile) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        /* 通過這個工廠設定一個緩沖區,當上傳的檔案大于這個緩沖區的時候,将他放到臨時檔案中; */
        factory.setSizeThreshold(1024 * 1024);// 緩沖區大小為1M
        factory.setRepository(tempFile);// 臨時目錄的儲存目錄,需要一個file
        return factory;
    }
    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 監聽長傳進度
        upload.setProgressListener(new ProgressListener() {

            // pBYtesRead:已讀取到的檔案大小
            // pContextLength:檔案大小
            @Override
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("總大小:" + pContentLength + "已上傳:" + pBytesRead);
            }
        });

        // 處理亂碼問題
        upload.setHeaderEncoding("UTF-8");
        // 設定單個檔案的最大值
        upload.setFileSizeMax(1024 * 1024 * 10);
        // 設定總共能夠上傳檔案的大小
        // 1024 = 1kb * 1024 = 1M * 10 = 10м

        return upload;

    }

    public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath) throws FileUploadException, IOException {
        String msg = "";
        // 把前端請求解析,封裝成FileItem對象
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {// 判斷上傳的檔案是普通的表單還是帶檔案的表單
                // getFieldName指的是前端表單控件的name;
                String name = fileItem.getFieldName();
                String value = fileItem.getString("UTF-8"); // 處理亂碼
                System.out.println(name + ": " + value);
            } else {// 判斷它是上傳的檔案

                // ============處理檔案==============

                // 拿到檔案名
                String uploadFileName = fileItem.getName();
                System.out.println("上傳的檔案名: " + uploadFileName);
                if (uploadFileName.trim().equals("") || uploadFileName == null) {
                    continue;
                }

                // 獲得上傳的檔案名/images/girl/paojie.png
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                // 獲得檔案的字尾名
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);

                /*
                 * 如果檔案字尾名fileExtName不是我們所需要的 就直按return.不處理,告訴使用者檔案類型不對。
                 */

                System.out.println("檔案資訊[件名: " + fileName + " ---檔案類型" + fileExtName + "]");
                // 可以使用UID(唯一識别的通用碼),保證檔案名唯
                // 0UID. randomUUID(),随機生一個唯一識别的通用碼;
                String uuidPath = UUID.randomUUID().toString();

                // ================處理檔案完畢==============

                // 存到哪? uploadPath
                // 檔案真實存在的路徑realPath
                String realPath = uploadPath + "/" + uuidPath;
                // 給每個檔案建立一個對應的檔案夾
                File realPathFile = new File(realPath);
                if (!realPathFile.exists()) {
                    realPathFile.mkdir();
                }
                // ==============存放位址完畢==============


                // 獲得檔案上傳的流
                InputStream inputStream = fileItem.getInputStream();
                // 建立一個檔案輸出流
                // realPath =真實的檔案夾;
                // 差了一個檔案;加上翰出檔案的名産"/"+uuidFileName
                FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);

                // 建立一個緩沖區
                byte[] buffer = new byte[1024 * 1024];
                // 判斷是否讀取完畢
                int len = 0;
                // 如果大于0說明還存在資料;
                while ((len = inputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                // 關閉流
                fos.close();
                inputStream.close();

                msg = "檔案上傳成功!";
                fileItem.delete(); // 上傳成功,清除臨時檔案
                //=============檔案傳輸完成=============
            }
        }
        return msg;

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
           
<!--    servlet注冊-->
<servlet>
    <servlet-name>FileServlet</servlet-name>
    <servlet-class>com.jezer.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>FileServlet</servlet-name>
    <url-pattern>/upload.do</url-pattern>
</servlet-mapping>
           
<%--index.jsp--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
<%--通過表單上傳檔案:
  get: 上傳檔案大小有限制;
  post: 上傳檔案大小沒有限制;
--%>
  <form action="${pageContext.request.contextPath}/ upload.do" enctype="multipart/form-data" method = "post">
  上傳使用者:<input type="text" name = "username"><br/>
  <p><input  type="file" name = "upload"></p>
  <p><input type="submit"> | <input type="reset"></p>
  </form>
  </body>
</html>
           
<%--info.jsp--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>
           
檔案上傳

課後鞏固:

下一篇: PUT上傳