如何使用 Scala 在 Play!2 中提供上传的文件? [英] How to serve uploaded files in Play!2 using Scala?

查看:21
本文介绍了如何使用 Scala 在 Play!2 中提供上传的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试允许用户将照片上传到服务器然后查看它们.上传过程如本指南所述.代码如下:

I'm trying to allow users to upload photos to the server and then view them. Uploading happens as described in this guide. Here is the code:

def upload = Action(parse.multipartFormData) { request =>
  request.body.file("picture").map { picture =>
    import java.io.File
    val filename = picture.filename 
    val contentType = picture.contentType
    picture.ref.moveTo(new File("/tmp/picture"))
    Ok("File uploaded")
  }.getOrElse {
    Redirect(routes.Application.index).flashing(
      "error" -> "Missing file"
    )
  }
}

我不清楚如何将上传的图像提供给想要查看它们的用户.现在我在自己的机器上托管服务器,因此指南中的代码片段将文件写入我的 D: 驱动器,该驱动器不能(也不应该)从 Internet 上获得.据我所知,有两个选项:

It is unclear to me how to serve the uploaded images back to users that want to see them. Right now I am hosting the server on my own machine, so the code snippet from the guide writes the files to my D: drive, which isn't (and shouldn't be) available from the Internet. As far as I can see there are 2 options:

  1. 将照片存储在我的项目(专用于资产的文件夹)中的/public 文件夹下.请参阅此处:http://www.playframework.org/documentation/2.0/Assets

编写我自己的控制器,从我的驱动器中从自定义位置提供图像.

Write my own controller that servs images form custom locations from my drive.

对于 1,我不确定这是否是资产的目的.对于2,我不知道如何编写这样的控制器.

For 1, I'm not sure if that is the purpose of assets. For 2, I have no idea how to write such a controller.

推荐答案

2.0.3 将采用 外部资产控制器 可能(误)用于此.编写这样的控制器并不神奇,你有一个预定义的文件夹,你的所有上传文件都保存在那里,这就是你从中读取它们的地方.在数据库中保存(唯一的)文件名.

2.0.3 will feature an external Assets controller which might be (mis)used for this. Writing such a controller is no magic though, you have predefined folder where all your uploads are saved, and that's where you read them from. In the database you save the (unique) file name.

另一种方法是将上传的文件保存在数据库中.我们使用 MongoDB 中的 GridFS 来做到这一点.自定义控制器将它们返回给用户.通过这种方式,您的数据将存储在一个中央位置,这也使备份和恢复变得更加简单.

A different approach would be to save the uploaded files in the database. We do this with GridFS in MongoDB. A custom controller serves them back to the user. This way your data is stored in one central place, which also makes backups and recoveries simpler.

这篇关于如何使用 Scala 在 Play!2 中提供上传的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆