如何从前端下载文件 - Java HTML

问题描述 投票:0回答:1

我点击前端的按钮时想下载文件。

前端

<td><a name="${flow.name}" data-toggle="tooltip" title="Report" class="generateReport"><span class="far fa-file-excel"></span></a></td>

调节器

@RequestMapping(value = "/flow/generate-report" , method = RequestMethod.GET)
public @ResponseBody void generateFlowReport(@RequestParam("flowName") String flowName) {
    TestFlow.generateReport(flowName);
}

public static void generateReport(String flowName) {

//code to generate the file

  // Write the output to a file
    FileOutputStream fileOut;
    try {
        new File(FILE_DIR).mkdirs();
        fileOut = new FileOutputStream(FILE_PATH);
        workbook.write(fileOut);
        fileOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我现在如何将其传递给前端?

javascript java jquery html spring
1个回答
0
投票

为了给你一个想法,这就是我在Spring MVC中的做法:

@RequestMapping(value = "/yourRequestUrl",
            method = RequestMethod.GET,
            produces = {MediaType.APPLICATION_OCTET_STREAM_VALUE, "application/vnd.ms-excel"})
@ResponseBody
public Resource generate(HttpServletResponse response) throws Exception {
    return runJob(response);
}

在我的runJob方法中,我执行以下操作:

private Resource runJob(HttpServletResponse response) throws IOException {

    final String fileLocation = "yourFileLocation";
    response.setHeader("Content-Disposition",
            "attachment; filename=yourFileName");
    response.setContentType("application/vnd.ms-excel");
    return new FileSystemResource(fileLocation);
}
© www.soinside.com 2019 - 2024. All rights reserved.