[學習筆記]Java下載文件

/**
     * 完成功能:使瀏覽器自帶下載工具下載某文件
     * @param request
     * @param response
     * @param docPath   需要下載文件的路徑
     */
    public static void checkDoc(HttpServletRequest request, HttpServletResponse response,String docPath) {
        File f=new File(docPath);
        String filename = docPath.substring(docPath.lastIndexOf("/") + 1);
        try {
            String downloadFilename = filename;
            String agent = request.getHeader("User-Agent");
            if (agent.contains("MSIE")) {
                downloadFilename = URLEncoder.encode(filename, "utf-8");
                downloadFilename = filename.replace("+", " ");
            } else if (agent.contains("Firefox")) {
                BASE64Encoder base64Encoder = new BASE64Encoder();
                downloadFilename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
            } else {
                downloadFilename = URLEncoder.encode(filename, "utf-8");

            }
            response.setContentType(request.getSession().getServletContext().getMimeType(filename));
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);

            InputStream in = new FileInputStream(docPath);
            OutputStream out = response.getOutputStream();
            IOUtils.copy(in, out);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章