1. 程式人生 > >java實現檔案下載功能,自動彈出儲存視窗

java實現檔案下載功能,自動彈出儲存視窗

public void download() {
        String filePath = this.queueService.getCsvFilePathById(id);
        try {
            File file = new File(filePath);
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);
            fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename="+fileName);
            String len = String.valueOf(file.length());
            response.setHeader("Content-Length", len);
            OutputStream out = response.getOutputStream();
            FileInputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while((n=in.read(b))!=-1){
                out.write(b, 0, n);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

以上是程式碼,下面是同樣的程式碼,只是多了一些註釋:

public void download() {
        String filePath = this.queueService.getCsvFilePathById(id);//所要下載的檔案路徑,從資料庫中查詢得到,當然也可以直接寫檔案路徑,如:C:\\Users\\Administrator\\Desktop\\csv\\號碼_utf8_100.csv
        try {
            File file = new File(filePath);
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);//得到檔名
            fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");//把檔名按UTF-8取出並按ISO8859-1編碼,保證彈出視窗中的檔名中文不亂碼,中文不要太多,最多支援17箇中文,因為header有150個位元組限制。
            response.setContentType("application/octet-stream");//告訴瀏覽器輸出內容為流
            response.addHeader("Content-Disposition", "attachment;filename="+fileName);//Content-Disposition中指定的型別是檔案的副檔名,並且彈出的下載對話方塊中的檔案型別圖片是按照檔案的副檔名顯示的,點儲存後,檔案以filename的值命名,儲存型別以Content中設定的為準。注意:在設定Content-Disposition頭欄位之前,一定要設定Content-Type頭欄位。
            String len = String.valueOf(file.length());
            response.setHeader("Content-Length", len);//設定內容長度
            OutputStream out = response.getOutputStream();
            FileInputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while((n=in.read(b))!=-1){
                out.write(b, 0, n);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }