稍后在Scala中定义一个val

时间:2014-05-25 20:20:26

标签: scala scope

我使用此代码将表单上传的图像保存到DB:

  def saveImage(userIdSource: String) = Action.async(gridFSBodyParser(gridFS)) { request =>
    // here is the future file!
    val futureFile = request.body.files.head.ref
    // when the upload is complete, we add the article id to the file entry (in order to find the attachments of the article)

    val futureUpdate = for {
      file <- futureFile
      // here, the file is completely uploaded, so it is time to update the user
      updateResult <- {

        gridFS.files.update(
          BSONDocument("_id" -> file.id),
          BSONDocument("$set" -> BSONDocument("metadata" ->
            BSONDocument("user" -> BSONObjectID(userIdSource),
              "size" -> "original"))))

        val iterator = gridFS.enumerate(file).run(Iteratee.consume[Array[Byte]]())
        iterator.flatMap {
          bytes => {
            // Create resized image
            val enumerator: Enumerator[Array[Byte]] = Enumerator.outputStream(
              out => {
                Image(bytes).bound(120, 120).writer(Format.JPEG).withCompression(90).write(out)
              }
            )

            val data = DefaultFileToSave(
              filename = file.filename,
              contentType = file.contentType,
              uploadDate = Some(DateTime.now().getMillis),
              metadata = file.metadata ++ BSONDocument(
                "user" -> BSONObjectID(userIdSource),
                "size" -> "thumb"
              )
            )

            Logger.warn(s"Saving resized image: [id=$userIdSource, metadata=${data.metadata}}]")
            gridFS.save(enumerator, data).map {
              image => Some(image)
            }
          }
        }
      }
    } yield updateResult

    futureUpdate.flatMap {
      case _ =>  //Some(_)

        val img = Image(BSONObjectID(userIdSource), DateTime.now(), None)
       //  insert the user
        val futureResult2 = snapsCollection.insert(img)
     //    when the insert is performed, send a OK 200 result
        futureResult2.map(_ => Ok("saved"))
    }.recover {
      case e => InternalServerError(e.getMessage())
    }
  }

此代码从表单中获取图像并将其存储在Mongo DB Grid FS中两次:

  • 原始图片
  • 拇指图像

我想在“img”对象中存储2个附加参数:

  • 原始图片的ID - 存储在“file.id”
  • 拇指图像的ID - 存储在“image.id”

如何将这两个值传递给:“futureUpdate.flatMap”?

1 个答案:

答案 0 :(得分:3)

将yield语句更改为元组(updateResult, file.id, image.id)然后在futureUpdate.flatMap的模式匹配中提取它们。