如何在 Play 应用程序中访问上传的 JSON 文件的内容
How to access contents of an uploaded JSON file in a Play application
我想使用 Play application/api.JSON 将 JSON 文件的内容上传到我的数据库。
我的 HTML 视图如下所示:
@main("Welcome to Play") {
<h1> Upload a JSON file </h1>
@helper.form(action = routes.Application.upload, 'enctype -> "text/json") {
<input type="file" name="jsonFile">
<p>
<input type="submit" value="Upload">
</p>
}
}
我在控制器中定义了我的上传方法。理想情况下,我想将内容上传到 Cassandra,但首先我必须访问文件本身的内容。
def upload = Action { request =>
val data = request.body.asJson / toString
Ok("Got: " + data)
}
我分别得到(对于 asJson
或 toString)
Got: None / Got: AnyContentAsFormUrlEncoded(Map(jsonFile -> ArrayBuffer(file.json)))
我的file.json
的格式是:
[{ "name": "alice", "age": 22}, { "name": "bob", "age": 23}]
而且我已经在 JSON lint 中验证了它的格式正确。基本上我似乎无法从文件中正确提取内容。
那是因为您没有使用 application/json
的 Content-Type
进行请求,因此您请求 body/payload 不是 JSON。您实际上是在使用 application/x-www-form-urlencoded
的 Content-Type
(您可以通过使用浏览器检查器)。
这是你必须做的:
- 如果您希望用户使用 Web 表单提交文件,请执行适当的 file upload
- 读取文件内容并发送给Cassandra。
我想使用 Play application/api.JSON 将 JSON 文件的内容上传到我的数据库。
我的 HTML 视图如下所示:
@main("Welcome to Play") {
<h1> Upload a JSON file </h1>
@helper.form(action = routes.Application.upload, 'enctype -> "text/json") {
<input type="file" name="jsonFile">
<p>
<input type="submit" value="Upload">
</p>
}
}
我在控制器中定义了我的上传方法。理想情况下,我想将内容上传到 Cassandra,但首先我必须访问文件本身的内容。
def upload = Action { request =>
val data = request.body.asJson / toString
Ok("Got: " + data)
}
我分别得到(对于 asJson
或 toString)
Got: None / Got: AnyContentAsFormUrlEncoded(Map(jsonFile -> ArrayBuffer(file.json)))
我的file.json
的格式是:
[{ "name": "alice", "age": 22}, { "name": "bob", "age": 23}]
而且我已经在 JSON lint 中验证了它的格式正确。基本上我似乎无法从文件中正确提取内容。
那是因为您没有使用 application/json
的 Content-Type
进行请求,因此您请求 body/payload 不是 JSON。您实际上是在使用 application/x-www-form-urlencoded
的 Content-Type
(您可以通过使用浏览器检查器)。
这是你必须做的:
- 如果您希望用户使用 Web 表单提交文件,请执行适当的 file upload
- 读取文件内容并发送给Cassandra。