建立文件並寫入信息,調用瀏覽器進行下載

private String downloadFile(HttpServletRequest request, HttpServletResponse response,String str) {
    File file = null;
    FileOutputStream fos = null;
    PrintStream ps = null;
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    ServletOutputStream out = null;
    try {
        //建立臨時文件並寫入內容
        file = File.createTempFile("test", ".txt");
        fos = new FileOutputStream(file);
        ps = new PrintStream(fos);
        //寫入內容爲追加
        ps.print(str);
        //end
        //將文件轉換爲流
        out = response.getOutputStream();
        request.setCharacterEncoding("UTF-8");
        int buffer = 1024 * 10;
        byte data[] = new byte[buffer];
        //獲取文件輸入流
        fis = new FileInputStream(file);
        int read;
        bis = new BufferedInputStream(fis, buffer);
        //拼裝請求頭
        response.setContentType("application/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=test.txt");
        while ((read = bis.read(data)) != -1) {
            out.write(data, 0, read);
        }
    } catch (Exception e) {
        try {
            ps.close(); //關閉流
            fis.close();
            out.close();
            bis.close();
            file.deleteOnExit(); //當程序退出時,刪除臨時文件
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        e.printStackTrace();
    } finally {
        try {
            ps.close(); //關閉流
            fis.close();
            out.close();
            bis.close();
            file.deleteOnExit(); //當程序退出時,刪除臨時文件
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
    return "";
}

注:下載文件提交方式必須是form提交,ajax提交不能調用瀏覽器下載ajax

相關文章
相關標籤/搜索