使用ajax和spring控制器处理浏览器文件下载

时间:2015-05-20 08:02:57

标签: java ajax spring-mvc browser download

在一个项目中,我需要将一些参数从ajax POST传递给spring控制器,spring控制器将参数传递回java服务,该服务在服务器上的给定位置生成文件,并将文件路径返回给控制器。后控制器进一步将路径重定向到GET控制器。现在GET控制器应该允许浏览器下载文件。

除了最后一步,GET spring控制器在浏览器中按预期生成响应但没有浏览器下载窗口弹出文件下载,一切正常。请有人帮帮我。我已经挣扎了72个小时。

第一步(ajax请求)正常工作:

 function exportData(criteria) {

    return $http({
        method: 'POST',
        url: 'export/PDF',
        data: criteria,
        headers: {'Accept': 'application/pdf'}

});
    } 

第二步(POST控制器)工作正常:

@RequestMapping(value = "export/PDF", method = RequestMethod.POST)
  public final String getDataToExportPDF(Model model, @RequestBody String    toJsonCriteria,
        final RedirectAttributes ra) throws Exception {

    try {

        AuditInput ai = auditService.formatDataToExport(toJsonCriteria);
        List<AuditData> ad = auditService.dataToExport(ai);
        logger.info("inside pdf export Post method ");
        String path = auditPdfService.createPDFFile(ai, ad);
        logger.info("inside export Post method");
        logger.info("inside pdf export Post method path: " + path);
        ra.addFlashAttribute("path", path);
        return "redirect:/download.html"; 

    } catch (Exception e) {
        logger.error("inside export/PDF POST catch");           
        throw new IndiciumException("error creating audit PDF file");
    }

}   

第3步(GET控制器生成响应输出,但不提示下载):

@RequestMapping(value = "download", method = RequestMethod.GET)
public void downloadFile(
        @ModelAttribute("path") final String path, HttpServletResponse response) throws Exception {
    try {           
        logger.error("inside download get try");    

        File downloadFile = new File(path);
        FileInputStream inputStream = new FileInputStream(downloadFile);

        ServletOutputStream out = response.getOutputStream();

        byte[] bytes = IOUtils.toByteArray(inputStream);
        out.write(bytes);

        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename = " + downloadFile.getName()); 
        response.setHeader("X-Frame-Options", "ALLOWALL");
        response.flushBuffer();

        out.close();
        out.flush();
        logger.info("the path is: " + path);


    } catch (Exception e) {
        logger.error("inside download get catch");          
        throw new IndiciumException("Can't download the audit file");
    }


} 

1 个答案:

答案 0 :(得分:0)

尝试替换以下行

response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename = " + downloadFile.getName()); 
response.setHeader("X-Frame-Options", "ALLOWALL");

使用:

response.setContentType("application/octet-stream");
response.addHeader("Content-disposition", "attachment; filename=\"" + downloadFile.getName() + "\"");
response.addHeader("X-Frame-Options", "ALLOWALL");

我用&#34; addHeader&#34; s替换了&#34; setHeader&#34; s并在文件名中添加了额外的双引号并为我工作。

希望这会对你有所帮助。