Play: additional public / assets directory

后端 未结 1 699
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 05:22

In order to have a clean directory structure, I would like to make an additional assets folder public. I\'ve created a directory \'assets\' in my project folder, wrote an \'

相关标签:
1条回答
  • 2020-12-16 05:36

    I think the issue comes from the fact that the at method used is the default one used previously by Assets.

    I ran into the same issue at some point last year, where I wanted to serve images that would be stored in a external folder, a folder that is somewhere on disk, and here is how I coded this:

    I created a simple controller called Photos, that contained one Action:

    object Photos extends Controller {
    
      val AbsolutePath = """^(/|[a-zA-Z]:\\).*""".r
    
      /**
       * Generates an `Action` that serves a static resource from an external folder
       *
       * @param absoluteRootPath the root folder for searching the static resource files.
       * @param file the file part extracted from the URL
       */
      def at(rootPath: String, file: String): Action[AnyContent] = Action { request =>
        val fileToServe = rootPath match {
          case AbsolutePath(_) => new File(rootPath, file)
          case _ => new File(Play.application.getFile(rootPath), file)
        }
    
        if (fileToServe.exists) {
          Ok.sendFile(fileToServe, inline = true)
        } else {
          Logger.error("Photos controller failed to serve photo: " + file)
          NotFound
        }
      }
    
    }
    

    Then, in my routes, I defined the following:

    GET /photos/*file   controllers.Photos.at(path="/absolute/path/to/photos",file)
    

    This worked just fine for me. Hope this helps.

    PS: This was in addition to the normal Assets controller that helped serving js and css files.

    0 讨论(0)
提交回复
热议问题