【问题标题】:Getting the Play Framework to redirect to a Thank You page after file download下载文件后让 Play 框架重定向到感谢页面
【发布时间】:2021-05-23 13:17:30
【问题描述】:

我有以下代码用于下载文件,然后重定向到DownloadController.scalaPlay Framework 下的感谢页面


def thankView = SecuredAction(WithProvider[AuthType](CredentialsProvider.ID)) {
    implicit request: SecuredRequest[DefaultEnv, AnyContent] =>
      Ok(downloadThankView(request.identity))
}




def download = SecuredAction(WithProvider[AuthType](CredentialsProvider.ID)) {

    implicit request: SecuredRequest[DefaultEnv, AnyContent] =>

      val futureMaybeFile = downloadService.generateDownload(request.identity.userID)

      val maybeFile = Await.result(futureMaybeTempFile, 10 second)

      maybeFile match {

        case Some(file) =>

          Ok.sendFile(

            file,

            fileName = _ => Some(file.getName),

            onClose = () => {

              file.delete()

              // position (1) for placing the redirect, which doesn’t prevent the file download, but does not get executed
              Redirect(routes.DownloadController.thankView())

            }
          ).withHeaders(
              "HttpResponse.entity.contentType" -> "text/txt",
              "Content-Disposition" -> s"attachment; filename=${file.getName}"
            )

           // position (2) for placing the redirect which executes but prevents the file download
           Redirect(routes.DownloadController.thankView())
          

        case None =>
          Redirect(routes.InfoController.view(Messages(“oops.there.was.error"), Messages("download.title")))

      }

  }

当我将Redirect(routes.DownloadController.thankView()) 行放在sendFileonClose 部分时,它不会被执行;当它放在sendFile 之后时,它会执行但会阻止文件被下载。

我在这里缺少什么?我该如何解决这个问题?

【问题讨论】:

    标签: scala playframework


    【解决方案1】:

    从 HTTP 的角度来看,我认为这是不可行的:单个 HTTP 响应不能同时包含一个文件并重定向到其他地方。

    你应该有某种 html 页面:

    1. 触发文件下载(例如通过JS)
    2. 触发重定向到“谢谢”页面

    【讨论】:

    • 非常感谢。我明白为什么位置 (2) 不起作用。奇怪的是,据我所知,onClose 部分中带有重定向的相同代码既是下载又是重定向。然后我更改了代码以通过一些InfoController 显示消息,然后将其更改回当前状态。现在,它不起作用。
    • 那么我可以在Twirl Engine 中向下载按钮添加redirect 操作吗?
    • 当然,我不知道确切的语法。我猜这应该记录在 Play 文档中。
    • 你知道HTML代码的语法吗?我的意思是我想通过按下同一个按钮来触发两个动作。只有一个问题:第二个动作应该只执行一次,并且如果第一个动作成功完成。所以我认为如果我只知道语法,在Play 中做服务器端会更干净。在routes 文件中,我可以更改GETPOST 以使其工作吗?最终,我想对两个 HTTP 响应进行排序或将它们捆绑在一个响应中。
    • 恕我直言,您必须使用 JavaScript 在客户端处理该问题。你不能只使用 HTML
    猜你喜欢
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 2010-10-26
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多