1. 程式人生 > >當瀏覽器 直接開啟txt,png等時是直接讀取而不是下載時解決方法

當瀏覽器 直接開啟txt,png等時是直接讀取而不是下載時解決方法

當我們把檔案上傳到專案 後  資料庫會存入上傳檔案路徑,在頁面上時就會通過location.href='路徑'  來直接下載 但是這樣下載txt等檔案時 瀏覽器會直接開啟

所以換了種方式 ,通過流來進行下載,

而在返回的response必須加上頭        this.getResponse().addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));  告訴瀏覽器是附件  

 再設定輸出型別 告訴瀏覽器要下載檔案          this.getResponse().setContentType("application/octet-stream");

package com.controller;
 import com.tis.helper.Utility;
import com.tis.mvc.ActionResult;
import com.tis.mvc.Controller;
import com.tis.mvc.HttpMethod;
import java.io.*;




    /**
     *通過流來下載 再加標頭
     * @author ysc
     */
    public class FileZipController extends Controller {
        @HttpMethod.HttpGet
        public ActionResult downfile()
        {
            String path =Utility.getRootPath()+"/"+Utility.getRequestStr("fileRpath");
            try {
                // path是指欲下載的檔案的路徑。
                File file = new File(path);
                // 取得檔名。
                String filename = file.getName();
                // 取得檔案的字尾名。
                String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
                // 以流的形式下載檔案。
                InputStream fis = new BufferedInputStream(new FileInputStream(path));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                this.getResponse().reset();
                // 設定response的Header
                this.getResponse().addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
                this.getResponse().addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(this.getResponse().getOutputStream());
                this.getResponse().setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return ActionResult.content("");
        }
    }