使用SpringBoot實現文件的下載


上一篇博客:使用SpringBoot實現文件的上傳

已經實現了文件的上傳,所以緊接着就是下載

首先還是html頁面的簡單設計

 

<form class="form-signin" th:action="@{/employee/File/download}" method="post">
<p><h1>下載文件</h1></p>
<p><h2>1.png</h2></p>
<p><input type="submit" value="下載"/></p>
<p style="color: red" th:text="${result}" th:if="${not #strings.isEmpty(result)}"></p>
</form>


待下載文件名為1.png

 

然后寫controller

package com.manager.controller.FileController;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class FileDownloadController {

@PostMapping("/employee/File/download")
public String testDownload( HttpServletResponse response ,Model model) {
//待下載文件名
String fileName = "1.png";
//設置為png格式的文件
response.setHeader("content-type", "image/png");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
byte[] buff = new byte[1024];
//創建緩沖輸入流
BufferedInputStream bis = null;
OutputStream outputStream = null;

try {
outputStream = response.getOutputStream();

//這個路徑為待下載文件的路徑
bis = new BufferedInputStream(new FileInputStream(new File("D:/upload/" + fileName )));
int read = bis.read(buff);

//通過while循環寫入到指定了的文件夾中
while (read != -1) {
outputStream.write(buff, 0, buff.length);
outputStream.flush();
read = bis.read(buff);
}
} catch ( IOException e ) {
e.printStackTrace();
//出現異常返回給頁面失敗的信息
model.addAttribute("result","下載失敗");
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//成功后返回成功信息
model.addAttribute("result","下載成功");
return "employee/EmployeeDownloadFile";
}
}

訪問頁面測試

 

 選擇下載路徑,點擊保存

 

 成功下載!

 


免責聲明!

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



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