javaweb上傳下載實例完整版解析(下)
更新時間:2017年01月24日 16:25:50 作者:求上進的程序媛
這篇文章主要為大家詳細解析了javaweb上傳下載實例,本文重點在于文件下載功能的實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下
一.顯示下載的文件資源
要將Web應(yīng)用系統(tǒng)中的文件資源提供給用戶進行下載,首先我們要有一個頁面列出上傳文件目錄下的所有文件,當(dāng)用戶點擊文件下載超鏈接時就進行下載操作,編寫一個ListFileServlet,用于列出Web應(yīng)用系統(tǒng)中所有下載文件。
1.1 文件下載頁面
download.html代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<title>下載文件顯示頁面</title>
</head>
<body>
<div id="fileName"></div>
</body>
<script >
$(function(){
download();
});
function download(){
$.ajax({
url: 'cloud/load/download',
type: 'POST',
dataType:'JSON',
cache: false,
processData: false,
contentType: false,
success : function(date){
var file="";
$.each(date,function(key,values){
var newKey = "/D:/Download/"+key;
file += "<div>"+key+" "+"<a href='cloud/load/downloadFile?fileName="+key+"'>"+"下載"+"</a>"+"</div>"+"<br>";
$(values).each(function(){
file+="\t"+this;
});
});
alert("success");
},
error : function(e){
alert("error");
}
});
}
</script>
</html>
1.2 controller
@RequestMapping(value = "/download", method = RequestMethod.POST)
@ResponseBody
public Map<String,String> download(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws ServletException, IOException{
Map<String,String> map = fileLoadService.doGet(request, response);
return map;
}
1.3 service
/**
* 文件下載顯示
* @ClassName: FileLoadServiceImpl
* @throws IOException
* @throws ServletException
*/
@Override
public Map<String,String> doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//獲取上傳文件的目錄
String uploadFilePath = "/D:/Download/";
//存儲要下載的文件名
Map<String,String> fileNameMap = new HashMap<String,String>();
//遞歸遍歷filepath目錄下的所有文件和目錄,將文件的文件名存儲到map集合中
listfile(new File(uploadFilePath),fileNameMap);
return fileNameMap;
}
public void listfile(File file,Map<String,String> map){
//如果file代表的不是一個文件,而是一個目錄
if(!file.isFile()){
//列出該目錄下的所有文件和目錄
File files[] = file.listFiles();
//遍歷files[]數(shù)組
for(File f : files){
//遞歸
listfile(f,map);
}
}else{
String realName = file.getName().substring(file.getName().indexOf("_")+1);
//file.getName()得到的是文件的原始名稱,這個名稱是唯一的,因此可以作為key,realName是處理過后的名稱,有可能會重復(fù)
map.put(file.getName(), realName);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
二.下載顯示的文件資源
2.1 controller
@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
@ResponseBody
public void downloadFile(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws ServletException, IOException{
String filename =request.getParameter("fileName");
fileLoadService.doGetFile(request, response ,filename);
}
2.2 service
/**
* 下載文件到本地 start
*/
@Override
public void doGetFile(HttpServletRequest request, HttpServletResponse response,String filename) throws ServletException,IOException {
//得到要下載的文件名
String fileName = filename;
fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
String fileSaveRootPath="/D:/Download";
File file = new File(fileSaveRootPath + "/" + fileName);
//如果文件不存在
if(!file.exists()){
request.setAttribute("message", "您要下載的資源已被刪除??!");
return;
}
//處理文件名
String realname = fileName.substring(fileName.indexOf("_")+1);
//設(shè)置響應(yīng)頭,控制瀏覽器下載該文件
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
InputStream fis = new BufferedInputStream(new FileInputStream(fileSaveRootPath + "\\" + fileName));
byte[] buffer = new byte[fis.available()];
fis.read(buffer); //讀取文件流
fis.close();
response.reset(); //重置結(jié)果集
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
response.addHeader("Content-Length", "" + file.length()); //返回頭 文件大小
response.setContentType("application/octet-stream"); //設(shè)置數(shù)據(jù)種類
OutputStream os = new BufferedOutputStream(response.getOutputStream());
os.write(buffer); // 輸出文件
os.flush();
os.close();
}
public void doPostFile(HttpServletRequest request, HttpServletResponse response,String filename)throws ServletException, IOException {
doGetFile(request, response,filename);
}
以上文件下載完成。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis異常java.sql.SQLSyntaxErrorException的問題解決
使用mybatis插入數(shù)據(jù)時出現(xiàn)java.sql.SQLSyntaxErrorException異常,本文就來介紹一下MyBatis異常的問題解決,具有一定的參考價值,感興趣的可以了解一下2023-08-08

