【java工具类】下载文件

FileUtil.java
/**
     * 下载文件
     * @param file;
     * @param response
     */
    public static void downloadFile(File file, HttpServletResponse response) {
        OutputStream os  = null;
        try {
            os = response.getOutputStream();
            String filePath = file.getName();
            if(!file.exists()){
                return;
            }

            response.reset();

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment;filename=\"%s\"", URLEncoder.encode(filePath,"UTF-8")));
            os.write(FileUtils.readFileToByteArray(file));
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            IOUtils.closeQuietly(os);
        }
    }

调用:

File file = new File("G:/pic");
downloadFile(file, response);
posted @ 2019-08-06 16:55  推土机27  阅读(220)  评论(0编辑  收藏  举报