java下载文件,返回文件流

有时候我们会下载服务器文件,需要将文件返回:

/**
     * 文件下载
     *
     * @param fileName
     * @param request
     * @param response
     * @throws Exception
     * @PathVariable注解参考https://www.cnblogs.com/williamjie/p/9139548.html
     */
    @ApiOperation("文件下载")
    @PostMapping("/download/{fileName}.log")
    public void download(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        //fileName为传入的要下载的文件的文件名,本示例下载的是日志文件所以后缀是.log
        fileName = URLDecoder.decode(fileName, "UTF-8");
        //要下载的文件的路径
        File logFile = new File("/usr/local/jar/log/" + fileName + ".log");
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(logFile));
             BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            long fileLength = logFile.length();
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            logger.error("错误信息: ", e);
        }
    }

如果使用commons上面代码可简化代码如下:
org.apache.commons.io的maven如下:


<dependency>
    <groupId>commons-iogroupId>
    <artifactId>commons-ioartifactId>
    <version>2.11.0version>
dependency>

简化代码:

    /**
     * 文件下载
     *
     * @param fileName
     * @param request
     * @param response
     * @throws Exception
     * @PathVariable注解参考https://www.cnblogs.com/williamjie/p/9139548.html
     */
    @ApiOperation("文件下载")
    @PostMapping("/download/{fileName}.log")
    public void download(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //fileName为传入的要下载的文件的文件名,本示例下载的是日志文件所以后缀是.log
        fileName = URLDecoder.decode(fileName, "UTF-8");
        //要下载的文件的路径
        File logFile = new File("/usr/local/jar/log/" + fileName + ".log");
        InputStream in = new FileInputStream(logFile);
        String filenamedisplay = URLEncoder.encode(fileName + ".log", "UTF-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + filenamedisplay);
        response.setContentType("application/x-download;charset=utf-8");
        OutputStream out = response.getOutputStream();
        IOUtils.copy(in, out);
        out.flush();
        in.close();
    }

你可能感兴趣的:(java,java,java,文件下载,Java文件下载到浏览器,Java服务器下载文件,Java文件下载)