我有一个模型
case class Person(
_id: ObjectId = new ObjectId,
empno: String,
name: String,
picture: String
)
我对如何处理form
,controller
和view
上的图片上传的图片有些丢失。感谢样品的帮助,或将我指向正确的方向。
此答案使用gridfs,但是您可以使用upload
方法中的文件来完成您想要的操作。
表格视图:
@helper.form(routes.Application.upload, 'enctype -> "multipart/form-data") {
@helper.inputFile(form("photo"))
<button type="submit">upload</button>
}
显示视图:
<img src='@routes.Application.getPhoto(fileId)'/>
控制器:
def upload = Action(parse.multipartFormData) { request =>
request.body.file("photo") match {
case Some(photo) =>
val gridFs = salat.gridFS("photos")
val uploadedFile = gridFs.createFile(photo.ref.file)
uploadedFile.contentType = photo.contentType.orNull
uploadedFile.save()
Ok(...)
case None => BadRequest("no photo")
}
}
def getPhoto(file: ObjectId) = Action {
import com.mongodb.casbah.Implicits._
val gridFs = salat.gridFS("photos")
gridFs.findOne(Map("_id" -> file)) match {
case Some(f) => SimpleResult(
ResponseHeader(OK, Map(
CONTENT_LENGTH -> f.length.toString,
CONTENT_TYPE -> f.contentType.getOrElse(BINARY),
DATE -> new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", java.util.Locale.US).format(f.uploadDate)
)),
Enumerator.fromStream(f.inputStream)
)
case None => NotFound
}
}
路由:
GET /upload controllers.Application.upload
GET /photos/:file controllers.Application.getPhoto(file: ObjectId)