Book Image

Play Framework Cookbook - Second Edition

By : Alexander Reelsen, Giancarlo Inductivo
Book Image

Play Framework Cookbook - Second Edition

By: Alexander Reelsen, Giancarlo Inductivo

Overview of this book

<p>As web and mobile systems become more sophisticated, anchoring systems in a mature, solid framework has become increasingly important. Play 2 provides developers with the necessary tools to build robust web applications.</p> <p>This book is a compilation of useful recipes aimed at helping developers discover the power of Play 2. The introductory section serves as a primer to Play Framework, wherein all the fundamentals of the framework are covered extensively. It then explains the usage of controllers and how modules can be leveraged for optimal performance. Next, the book walks you through creating and using APIs, followed by extensive real-world applications. Finally, you will learn to manage applications post production.</p>
Table of Contents (15 chapters)
Play Framework Cookbook Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Utilizing MongoDB and GridFS


For this recipe, we will explore how to store and deliver files with Play applications by using MongoDB and GridFS. We will continue by adding to the previous recipe. As with the previous recipe, this recipe will be Scala only.

How to do it…

Let's take the following steps:

  1. Run the foo_scala application with Hot-Reloading enabled:

        activator "~run"
    
  2. Modify foo_scala/app/controllers/WarehouseController.scala by adding the following content:

        import java.text.SimpleDateFormat
        import play.api.libs.iteratee.Enumerator
    
        def upload = Action(parse.multipartFormData) { request =>
            request.body.file("asset") match {
              case Some(asset) => {
                val gridFs = Warehouse.assets
                val uploadedAsset = gridFs.createFile(asset.ref.file)
                uploadedAsset.filename = asset.filename
                uploadedAsset.save()
    
                Ok("Asset is available at http://localhost:9000/warehouses/assets/%s".format(uploadedAsset.id))
      ...