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

时间:2018-02-28 12:57:41

标签: javascript java jquery html spring

当我点击前端的按钮时,我想下载一个文件。

前端

<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();
    }
}

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

1 个答案:

答案 0 :(得分: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);
}