這篇寫下載。
1.實現思路
上一篇的數據庫設計中,我們有一個字段始終沒有用到fileName,這是用來給Layer對象存儲文件名的,以此來完成文件與對象的對應,
預覽:
2.Code
View層:
首先是加載數據表格異步的時候 我們就獲取到了fileName,然後通過獲取當前行,來獲取當前的fileName文件名。
table.on('tool(test)', function(obj) {
var data = obj.data; //獲得當前行數據
var layEvent = obj.event; //獲得 lay-event 對應的值(也可以是表頭的 event 參數對應的值)
var tr = obj.tr; //獲得當前行 tr 的DOM對象
$ = layui.jquery;
if (layEvent === 'download') { //刪除
var fileName = data.fileName;
window.location="layer/download?fileName="+fileName;
}
});
然後不論是上傳下載使用ajax都不推薦(上傳下載都屬於獲取資源請求,a標籤等即可實現,而ajax是js異步的封裝請求,兩者實現目標不一樣)
這裏使用window.location來實現對文件的請求。
然後是Controller層:
//下載
@RequestMapping(value = "Index/layer/download")
@ResponseBody
public Map<String,Object> downloadOne(HttpServletRequest req,HttpServletResponse response) throws IOException{
String fileName = req.getParameter("fileName");// 設置文件名,根據業務需要替換成要下載的文件名
// String layerId = req.getParameter("layerId");
String downloadDir = req.getSession().getServletContext().getRealPath("/") +"upload/";
// String savePath = req.getSession().getServletContext().getRealPath("/") +"download/";
downloadDir=downloadDir.substring(0,downloadDir.length()-1);
downloadDir=downloadDir+"\\";//下載目錄
String realPath=downloadDir+fileName;//
File file = new File(realPath);//下載目錄加文件名拼接成realpath
if(file.exists()){ //判斷文件父目錄是否存在
// response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件輸入流
BufferedInputStream bis = null;
OutputStream os = null; //輸出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("----------file download" + fileName);
try {
bis.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return api.returnJson(2,"fail"+realPath+fileName);
}
主要就是調IO流,然後下載罷了,拼一下路徑和文件名即可
3.效果一覽
覺得有用就給顆小💗💗吧~
**項目僅供測試學習使用,拒絕任何形式的商業用途,轉侵刪。
項目源碼關注公衆號Code In Java,回覆"SpringBoot上傳下載"即可獲取。除此之外,還有Java學習圖譜,數據結構與算法資料等各種資料都可以在後臺獲取。**
關注公衆號:Code In Java
資源,項目,面試題一網打盡
希望與你成爲Java技術的同路人