如何在Spring中返回文件以及包含一些有关文件信息的对象?

时间:2019-06-27 12:20:58

标签: spring-boot

我已经有一种下载Excel文件的方法。但是,我想同时下载excel文件并获取有关该excel文件的信息(这是对象)。

我尝试了以下代码,但是它仅返回excel文件。

@GetMapping(value = "/export")
public ImportResult exportAlarms(HttpServletRequest request,
                                           HttpServletResponse response) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try (Workbook workbook = new XSSFWorkbook()) {
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerFont.setColor(IndexedColors.BLUE.getIndex());

        CellStyle headerCellStyle = workbook.createCellStyle();
        headerCellStyle.setFont(headerFont);
        ImportResult result = alarmExporter.exportAlarms(workbook, headerCellStyle, null);

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());

        response.addHeader("Content-Disposition", "attachment; filename=\"alarms.xlsx\"");
        workbook.write(response.getOutputStream());
        response.getOutputStream().flush();
        return result;

    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

这是ImportResult代码:

public class ImportResult {

private final int successCount;

private final int failCount;

private final List<String> errors;

public ImportResult(int successCount, int failCount, List<String> errors) {
    this.successCount = successCount;
    this.failCount = failCount;
    this.errors = errors == null ? new ArrayList<>() : new ArrayList<>(errors);
}

public int getSuccessCount() {
    return successCount;
}

public int getFailCount() {
    return failCount;
}

public List<String> getErrors() {
    return Collections.unmodifiableList(errors);
}

public boolean hasErrors() {
    return !errors.isEmpty();
}

public ImportResult combine(ImportResult another) {
    int successCount = another.getSuccessCount() + this.getSuccessCount();
    int failCount = another.getFailCount() + this.getFailCount();
    List<String> errors = new ArrayList<>(another.getErrors());
    errors.addAll(this.getErrors());
    return new ImportResult(successCount, failCount, errors);
}

0 个答案:

没有答案