其他分享
首页 > 其他分享> > 下载文件

下载文件

作者:互联网

1.

    @ApiOperation(value = "导出记录")
    @PostMapping("/excel")
    public ResponseEntity<byte[]> export(@RequestParam String type, @RequestBody JSONObject obj) {
        Pair<String, byte[]> data = exportExcelManagerService.exportExcel(type, obj);
        String fileName = data.getKey() + "-" + System.currentTimeMillis() + ".xlsx";
        try {
            return writeFile(fileName, data.getValue());
        } catch (Exception exception) {
            log.error("导出excel异常!类型:{},请求:{}", type, obj);
            throw new RuntimeException("导出excel异常");
        }
    }

    private static <T> ResponseEntity<byte[]> writeFile(String fileName, byte[] buffer) throws IOException {
        String encodeFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(encodeFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(encodeFileName);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDispositionValue.toString())
                .header("Cache-Control", "no-cache, no-store, must-revalidate")
                .header("Pragma", "no-cache")
                .header("Expires", "0")
                .body(buffer);
    }

 

标签:文件,String,no,fileName,header,下载,contentDispositionValue,append
来源: https://www.cnblogs.com/zhshlimi/p/16623849.html