Spring Boot - 重定向到url并提供文件下载

时间:2017-05-22 11:16:28

标签: spring spring-mvc model-view-controller

Spring中有没有办法提供文件下载和视图? 我想给用户一个自动下载,并通过一个新的html页面通知用户。

 @RequestMapping(value = "/abgeschlossen/{bildcodes}")
 @ResponseBody
  public byte[]  download(@PathVariable List<String> bildcodes,
  HttpServletRequest request, HttpServletResponse response) throws 
IOException, ServletException {

    response.setContentType("application/zip");
    response.setStatus(HttpServletResponse.SC_OK);
    response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");

    //creating byteArray stream, make it bufforable and passing this buffor to ZipOutputStream
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
    ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);


    //packing files
    for (int i = 0;i<bildcodes.size();i++){
        Bild a = bildDao.findBildByCode(bildcodes.get(i));
        if (a!=null) {
            //new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
            zipOutputStream.putNextEntry(new ZipEntry("Bild" + i + ".jpg"));
            ByteArrayInputStream fileInputStream = new ByteArrayInputStream(a.getDatei());

            IOUtils.copy(fileInputStream, zipOutputStream);

            fileInputStream.close();
            zipOutputStream.closeEntry();
        }
    }

    if (zipOutputStream != null) {
        zipOutputStream.finish();
        zipOutputStream.flush();
        IOUtils.closeQuietly(zipOutputStream);
    }

    IOUtils.closeQuietly(bufferedOutputStream);
    IOUtils.closeQuietly(byteArrayOutputStream);
    //RequestDispatcher rd=request.getRequestDispatcher("/abgeschlossen/fertig");
    //rd.forward(request, response);//method may be include or forward
    return byteArrayOutputStream.toByteArray();
}

我同时需要返回我的观点

return "finished.html";

我找到了一些HTMLresponse的解决方案,但是我遇到了许多重定向的问题。

希望有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

您可以向finished.html

添加AJAX调用

OR

调用AJAX下载脚本,并在启动成功后重定向到finished.html

请参阅Handle file download from ajax post