1. 程式人生 > >Java檔案下載,自定義下載名稱

Java檔案下載,自定義下載名稱

檔案下載我們經常會用到,把資源放到伺服器然後開啟就可以訪問資源了。。。就以tomcat伺服器為例
這裡寫圖片描述
我伺服器上有個img資料夾裡面有123.jpg的檔案,我啟動伺服器
這裡寫圖片描述

可以訪問到這個圖片 , 但是路徑名稱和檔名稱是固定的 ;但是我們發現有些下載連結下載下來的檔案檔名稱是變化了 。。。。 還有就是,這個圖片我本來是想下載了, 但是瀏覽器卻預設給我展示了 。。。。 這個就尷尬了 。。
如果自定義檔案的名稱了 ? 直接上程式碼。。。


import java.io.FileInputStream;
import java.io.InputStream;
import java.io
.OutputStream; import java.util.Date; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping
; import net.sf.json.JSONObject; @RequestMapping("/test") @Controller public class TestController { private static Logger logger = Logger.getLogger(TestController.class); @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "/download.do") public void downloadAction(String fileName,HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType
("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); String path = "/Users/apple/Desktop/"+fileName; InputStream inputStream = new FileInputStream(path); byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read()) != -1) { inputStream.read(buffer, 0, len); } inputStream.close(); } } http://127.0.0.1:8088/xxddeng/test/download.do?fileName=100.wmv

這是一個介面 , 介面接收一個引數
這裡寫圖片描述

這裡寫圖片描述

我們可以看到,下載檔案就像呼叫介面一樣可以自定義 。。。。
其實有時候我們還會有一種需求就是有多個檔案然後需要壓縮下載

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping(value = "/download2.do")
    public void download2Action(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String downloadName = "壓縮包.zip";
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename=" + downloadName);
        String path1 = "/Users/apple/Desktop/100.wmv";
        String path2 = "/Users/apple/Desktop/101.wmv";
        String path3 = "/Users/apple/Desktop/102.wmv";
        File files[] = new File[] { new File(path1), new File(path2), new File(path3) };

        File zipFile = new File("/Users/apple/Desktop/壓縮包.zip");
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); // 宣告壓縮流物件
        for (File file : files) {
            InputStream input = new FileInputStream(file); // 定義檔案的輸入流
            zipOut.putNextEntry(new ZipEntry(file.getName())); // 設定ZipEntry物件
            zipOut.setComment("hebiao.online"); // 設定註釋
            int temp = 0;
            while ((temp = input.read()) != -1) { // 讀取內容
                zipOut.write(temp); // 壓縮輸出
            }
            input.close(); // 關閉輸入流
        }
        zipOut.close(); // 關閉輸出流

    }