如何使用play.WS获取java.io.file?

时间:2014-11-17 07:03:56

标签: java file scala playframework byte

我可以bytes使用Play WS,但我需要java.io.file上传AWS S3

WS.url("http://media1.santabanta.com/full1/Indian%20%20Celebrities%28F%29/Yami%20Gautam/yami-gautam-27a.jpg").get().map { response =>
  val in = response.getAHCResponse.getResponseBodyAsBytes
Ok("yami")
}

现在我如何获得java.io.File

1 个答案:

答案 0 :(得分:2)

正如@Mikesname建议的那样,尝试将字节写入临时文件,然后上传。使用play框架的promises和async功能。我相信你可以将这个java代码转换为scala作为你作业的一部分:

Promise<File> filePromise = WS.url("http://stackoverflow.com/questions/26967252/how-to-get-java-io-file-by-using-play-ws").get().map((r) -> {
    FileOutputStream out = null;
    File file = File.createTempFile("file", null);
    try {
        out = new FileOutputStream(file);
        InputStream bodyAsStream = r.getBodyAsStream();
        byte[] barr = new byte[8 * 1024];
        int read = 0;
        while ((read = bodyAsStream.read(barr)) != -1) {
            out.write(barr, 0, read);
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }
    return file;
});

filePromise.map((file) -> {
    // Use amazon service to upload.
    return file;
});