springboot下载文件

下载已存在的文件

@RequestMapping("/downloadWithGivenFile")
public void downloadWithGivenFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
    InputStream inputStream = this.getClass().getResourceAsStream("/template/mac地址上传模板.xlsx");
    try (OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
        response.setContentType("application/octet-stream");
        // 指定下载的文件名
        response.setHeader("Content-disposition", "attachment; filename=" + new String("mac地址上传模板.xlsx".getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.flush();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

动态写入文件

@RequestMapping("/downloadWithData")
@ResponseBody
public Object downloadWithData(HttpServletResponse response) throws Exception {
    List<String> data = new ArrayList<>();
    //组装数据

    try (OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
        response.setContentType("application/octet-stream");
        // 指定下载的文件名
        response.setHeader("Content-disposition", "attachment; filename=" + new String("测试文件.txt".getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));

        int waitFlushCount = 0;
        for (String oneLine : data) {
            waitFlushCount++;
            bufferedWriter.write(oneLine);
            bufferedWriter.newLine();
            if (waitFlushCount == 5000) {
                bufferedWriter.flush();
            }
        }
        bufferedWriter.flush();
        bufferedWriter.close();
        outputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

results matching ""

    No results matching ""