1. 程式人生 > >javaweb基於spring MVC的上傳下載例項(下)

javaweb基於spring MVC的上傳下載例項(下)

檔案下載

  要將Web應用系統中的檔案資源提供給使用者進行下載,首先我們要有一個頁面列出上傳檔案目錄下的所有檔案,當用戶點選檔案下載超連結時就進行下載操作,編寫一個ListFileServlet,用於列出Web應用系統中所有下載檔案。

1.1 搭建前臺頁面
download.html程式碼如下:

<!DOCTYPE HTML>
<html>
<head> <title>下載檔案顯示頁面</title></head> 
<body>
    <div id="fileName"></div>
</body> </html>

對download.html新增js:

<script >
<!-- 初始化載入download()函式 -->
$(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+"&nbsp;&nbsp;"+"<a href='cloud/load/downloadFile?fileName="+key+"'>"+"下載"+"</a>"+"</div>"+"<br>"; $(values).each(function
(){
file+="\t"+this; }); }); alert("success"); }, error : function(e){ alert("error"); } }); }
</script>

說明:
在spring mvc框架下,通過spring註解,這裡的ajax的url指向的是UploadAndDownloadController的download()方法

1.2 controller
UploadAndDownloadController.Java程式碼如下:

 package com.cloud.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cloud.web.service.FileLoadService;

@Controller
@RequestMapping("/load")
public class UploadAndDownloadController {

    @Resource
    public FileLoadService fileLoadService;

    /**
     * 顯示要下載的檔案
     * @param request
     * @param response
     * @param model
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @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;
    }

    /**
     * 檔案下載到本地
     * @param request
     * @param response
     * @param model
     * @throws ServletException
     * @throws IOException
     */
    @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);
    }

}

1.3 service介面
FileLoadService程式如下:

package com.cloud.web.service;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface FileLoadService {
    Map<String,String> doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;

    void listfile(File file,Map<String,String> map);

    void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;

    void  doGetFile(HttpServletRequest request, HttpServletResponse response,String filename) throws ServletException, IOException;


}

1.4 service的實現類
FileLoadServiceImpl.java程式如下:

package com.cloud.web.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.cloud.web.service.FileLoadService;

@Service
public class FileLoadServiceImpl implements FileLoadService{

    /**
     * 待下載檔案的顯示
     */
    @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>();
        //遞迴遍歷uploadFilePath目錄下的所有檔案和目錄,將檔案的檔名儲存到map集合中
        listfile(new File(uploadFilePath),fileNameMap);//File既可以代表一個檔案也可以代表一個目錄
        //將Map集合返回頁面
        return fileNameMap;
    }    

     public void listfile(File file,Map<String,String> map){
        //如果file代表的不是一個檔案,而是一個目錄
        if(!file.isFile()){
        //列出該目錄下的所有檔案和目錄
        File files[] = file.listFiles();
        //遍歷files[]陣列
        for(File f : files){
        //遞迴
         listfile(f,map);
         }
    }else{
            String realName = file.getName().substring(file.getName().indexOf("_")+1);
            //file.getName()得到的是檔案的原始名稱,這個名稱是唯一的,因此可以作為key,realName是處理過後的名稱,有可能會重複
            map.put(file.getName(), realName);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

        /**
         * 將顯示的檔案下載到本地
         */
        @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);
            //設定響應頭,控制瀏覽器下載該檔案
            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();//重置結果集
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());  //返回頭 檔案大小
            response.setContentType("application/octet-stream");    //設定資料種類
            ///獲取返回體輸出權
            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);
           }
}

以上 檔案下載完成~