Scala Download file upload: Unable to write an instance of the form views.html.uploadFile.type in HTTP

I created a minimal Play website that allows users to upload a file. Although the code used is pretty simple, I cannot find the cause of 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 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>
}

In order for the controller to display the file upload form and process the downloaded 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 is my routesfile:

GET         /uploadForm          @controllers.FileUpload.uploadForm
POST        /upload              @controllers.FileUpload.handleUpload
+4
source share
1 answer

I missed the missing brackets in the controller action:

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

Adding them makes the application compiled.

+7
source

Source: https://habr.com/ru/post/1615960/


All Articles