Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Play file upload: Cannot write an instance of views.html.uploadFile.type to HTTP response

I created a minimal website in Play that lets users upload a file. Although the code involved is rather simple, I can't find the reason for this compilation error:

Cannot write an instance of views.html.uploadFile.type to HTTP response. Try to define a Writeable[views.html.uploadFile.type]

Here are the contents of views.uploadFile.scala.html:

@helper.form(action = routes.FileUpload.handleUpload, 'enctype -> "multipart/form-data") {
  File to upload: <input type="file" name="uploadedFile">

  <div> <input type="submit"> </div>
}

That's the controller displaying the file upload form and handling the uploaded file:

package controllers

import play.api.i18n.{MessagesApi, I18nSupport}
import play.api.mvc._
import javax.inject.Inject

class FileUpload @Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport {
  def uploadForm = Action {
    Ok(views.html.uploadFile)
  }

  def handleUpload = Action(parse.multipartFormData) { request =>
    import java.io.File
    request.body.file("uploadedFile") match {
      case Some(file) =>
        val fileName = file.filename
        val uploadDir = "/tmp/uploadedFiles/"
        file.ref.moveTo(new File(uploadDir + fileName))
        Ok(s"File uploaded: $fileName")

      case None =>
        Redirect(routes.FileUpload.uploadForm()).flashing(
          "error" -> "File invalid")
    }
  }
}

And for the sake of completeness, here's my routes file:

GET         /uploadForm          @controllers.FileUpload.uploadForm
POST        /upload              @controllers.FileUpload.handleUpload
like image 509
Matthias Braun Avatar asked Nov 15 '15 14:11

Matthias Braun


1 Answers

I overlooked the missing parentheses in the controller's action:

def uploadForm = Action {
  // instead of Ok(view.html.uploadFile)
  Ok(views.html.uploadFile()) 
}

Adding them makes the application compile fine.

like image 147
Matthias Braun Avatar answered Nov 15 '22 15:11

Matthias Braun