天天看點

MultipartResolver實作檔案下載下傳

首先在首頁添加下載下傳檔案的功能選項:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
<title>初始頁面</title>
</head>
<body>

<h3>
  <a href="${pageContext.request.contextPath}/Log/gologin">登入頁面</a>
</h3>
<h3>
<a href="${pageContext.request.contextPath}/Log/main">進入首頁</a>
</h3>
<h3>
  <a href="${pageContext.request.contextPath}/Upload/goinput">檔案上傳</a>
</h3>
<h3>
  <a href="${pageContext.request.contextPath}/Upload/godownload">檔案下載下傳</a>
</h3>
</body>
</html>
           

然後在Controller中寫請求:

//跳轉到下載下傳檔案界面
    @RequestMapping("/godownload")
    public String godownloads(){
        return "download";
    }
           
//下載下傳檔案
    @RequestMapping("/download")
    public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
        //要下載下傳的圖檔位址
        String path = request.getServletContext().getRealPath("input");
        String fileName = "Java開發學習路線.png";

        //設定response響應頭
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        //設定響應頭
        response.setHeader("Content-Disposition","attachment;fileName="+
                    URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        File file = new File(path,fileName);
        //讀取檔案-輸出流
        InputStream inputStream = new FileInputStream(file);
        //寫檔案-輸出流
        OutputStream outputStream = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
        //執行寫出操作
        while ((index=inputStream.read(buff))!=-1){
            outputStream.write(buff,0,index);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
        return "downloadSuccess";
    }
           

規定了要下載下傳檔案的路徑以及檔案名,更換要下載下傳的檔案隻需要改動這部分即可。

然後寫發送下載下傳請求的頁面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: shadowpee
  Date: 2021/1/25
  Time: 23:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/Upload/download">下載下傳圖檔</a>
<a href="${pageContext.request.contextPath}">回到首頁</a>

</body>
</html>

           

打開Tomcat伺服器試驗一下:

MultipartResolver實作檔案下載下傳

點選檔案下載下傳,跳轉到下載下傳檔案界面

MultipartResolver實作檔案下載下傳

點選發送下載下傳請求:

MultipartResolver實作檔案下載下傳

下載下傳成功,回到首頁。

上一篇: Java複習回顧