iT邦幫忙

2024 iThome 鐵人賽

DAY 19
0
Software Development

從Servlet到Spring MVC系列 第 19

Day18 Servlet - File Upload and File Download

  • 分享至 

  • xImage
  •  

前言

在Web專案裡多少都會遇到檔案上傳到Server或從Server端下載資料的需求,今日就來看看Java EE提供什麼樣子的解決方案

0、創建module

請參考Day05創建module

一、FileUpload

Servlet3.0起新增了Part interface,讓我們可以更簡單的處理檔案上下傳

  • HttpServletRequest調用getParts()
    若是多檔案上傳可以使用此方法,此方法回傳Collection的Part物件
  • HttpServletRequest調用getPart(String name)
  • MultipartConfig
    透過MultipartConfig對於上傳檔案相關設定檔
  • 寫入磁碟使用part.write()
  • 寫入DB使用part.getInputStream()

Demo

@MultipartConfig(
        fileSizeThreshold = 1024 * 1024   //1MB The size threshold after which the file will be written to disk
        ,maxFileSize = 5* 1024 * 1024     //5MB The maximum size allowed for uploaded files.
        ,maxRequestSize = 5* 5* 1024 * 1024  //5MB The maximum size allowed for multipart/form-data requests
)
@WebServlet("/UploadFileServlet")
public class UploadFileServlet extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        String filePath =  getServletContext().getRealPath("file_upload") ;
        System.out.println("filePath;"+filePath);

        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            String fileName = part.getSubmittedFileName();
            System.out.println("upload filename;"+fileName);
            part.write(filePath+File.separator+fileName);
        }
        System.out.println("file upload success!!");
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo Fileupload and Download</title>
</head>
<body>
    <h5>上傳檔案:</h5>
    <form action="/UploadFileServlet" method="post" enctype="multipart/form-data">
        <input type="file" name="選擇檔案">
        <input type="submit" value="上傳">
    </form>

</body>
</html>

訪問index.html上傳任意檔案
https://ithelp.ithome.com.tw/upload/images/20241003/20128084rgXMlkfI3o.png
上傳payload
https://ithelp.ithome.com.tw/upload/images/20241003/20128084Ff8mMO3tpg.png
server log
https://ithelp.ithome.com.tw/upload/images/20241003/20128084boaZigiHzB.png

二、FileDownload

  1. 文件下載透過ServletOutPutStream將檔案寫出
  2. 需設置Content-Type供瀏覽器解讀使用
  3. 設置Header Content-Disposition, attachment; filename=XXXC
  4. 中文檔名需要透過URLEncoder進行編碼
    create DownloadServlet
@WebServlet(urlPatterns = "/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String file = "火影忍者.jpg";

        String mimeType = getServletContext().getMimeType(file);
        res.setContentType(mimeType);
        //解決中文檔名問題
        String fileName = URLEncoder.encode(file, "UTF8");
        res.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");

        //io stream操作 method1
        String filePath = getServletContext().getRealPath("download")+ File.separator+file;
        FileInputStream is = new FileInputStream(filePath);
        ServletOutputStream outputStream = res.getOutputStream();
        byte[] bytes = is.readAllBytes();
        outputStream.write(bytes);
        is.close();

        //io stream操作 method2
        //getServletContext().getResourceAsStream("/download/"+file).transferTo(res.getOutputStream());

    }
}

index.html增加連結

<h5>下載檔案:</h5>
    <a href="DownloadServlet">Download</a>

https://ithelp.ithome.com.tw/upload/images/20241003/20128084SHrn1EiTY3.png

Reference


上一篇
Day17 Servlet - Listener
下一篇
Day19 Servlet - Error Handling
系列文
從Servlet到Spring MVC36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言