我在Play中创建了一个允许用户上传文件的最小网站。虽然所涉及的代码相当简单,但我无法找到编译错误的原因:
Cannot write an instance of views.html.uploadFile.type to HTTP response. Try to define a Writeable[views.html.uploadFile.type]
以下是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>
}
控制器显示文件上传表单并处理上传的文件:
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")
}
}
}
为了完整起见,请点击我的routes
文件:
GET /uploadForm @controllers.FileUpload.uploadForm
POST /upload @controllers.FileUpload.handleUpload
答案 0 :(得分:9)
我忽略了控制器动作中缺少的括号:
def uploadForm = Action {
// instead of Ok(view.html.uploadFile)
Ok(views.html.uploadFile())
}
添加它们可以使应用程序编译正常。