问题描述
我正在使用此代码在服务器上上传图像,这是我从此链接获得的 play upload
def upload = Action(parse.multipartFormData) { request =>
request.body
.file("picture")
.map { picture =>
val dataParts = request.body.dataParts;
val filename = Paths.get(picture.filename).getFileName
val fileSize = picture.fileSize
val contentType = picture.contentType
val picturePaths =
picture.ref.copyTo(
Paths.get(
s"/opt/docker/images/$filename"
),replace = true
)
if (dataParts.get("firstPoint") == None) {
val pointlocation = new Point_LocationModel(
dataParts.get("step").get(0),dataParts.get("backgroundTargetName").get(0),dataParts.get("x").get(0),dataParts.get("y").get(0),dataParts.get("z").get(0),dataParts.get("rotation").get(0),dataParts.get("note").get(0),dataParts.get("tag").get(0),dataParts.get("work_session_id").get(0),(picturePaths).toString
)
point_LocationRepository.create(pointlocation).map { data =>
Created(Json.toJson(data._2))
}
} else {
val jValuefirstPoint =
Json.parse(dataParts.get("firstPoint").get(0)).as[PointModel]
val jValuesecondPoint =
Json.parse(dataParts.get("secondPoint").get(0)).as[PointModel]
val pointlocation = new Point_LocationModel(
dataParts.get("step").get(0),Some(jValuefirstPoint),Some(jValuesecondPoint),(picturePaths).toString
)
point_LocationRepository.create(pointlocation).map { data =>
logger.info(s"repoResponse: ${data}");
Created(Json.toJson(data._2))
}
}
Ok(s"picturePaths ${picturePaths}")
}
.getorElse(Ok("Invalid Format"))
}
此代码运行良好,但在响应中我想从存储库中获取响应。我如何等待存储库的响应返回此内容?
你能告诉我我该怎么做吗? 提前致谢。
解决方法
如果我们将您的代码简化为基本部分,您将:
def upload = Action(parse.multipartFormData) { request =>
request.body
.file("picture")
.map { picture =>
if (someConditionA) {
someBusinessLogicA().map { data =>
Created(Json.toJson(data._2))
}
} else {
someBusinessLogicB().map { data =>
Created(Json.toJson(data._2))
}
}
Ok(s"picturePaths ${picturePaths}")
}
.getOrElse(Ok("Invalid Format"))
}
有两个问题:
- 你的
if/else
的回报被Ok(s"picturePaths ${picturePaths}")
吞没了 - 假设您的业务逻辑返回
Future[_]
,您需要到处“传播”未来
这样的事情应该可以工作:
def upload = Action.async(parse.multipartFormData) { request =>
request.body
.file("picture")
.map { picture =>
if (someConditionA) {
someBusinessLogicA().map { data =>
Created(Json.toJson(data._2))
}
} else {
someBusinessLogicB().map { data =>
Created(Json.toJson(data._2))
}
}
}
.getOrElse(Future.successful(Ok("Invalid Format")))
}
注意 Action.async
中的 Future
和 getOrElse
。