如何使用playframework中的网址上传照片? 我这样想:
URL url = new URL("http://www.google.ru/intl/en_com/images/logo_plain.png");
BufferedImage img = ImageIO.read(url);
File newFile = new File("google.png");
ImageIO.write(img, "png", newFile);
但也许还有另一种方式。最后,我必须得到文件和文件名。
控制器示例:
public static Result uploadPhoto(String urlPhoto){
Url url = new Url(urlPhoto); //doSomething
//get a picture and write to a temporary file
File tempPhoto = myUploadPhoto;
uploadFile(tempPhoto); // Here we make a copy of the file and save it to the file system.
return ok('something');
}
答案 0 :(得分:2)
要获取该照片,您可以使用Play WS API,后面的代码是从处理大型回复一节中的播放文档中提取的示例,我建议您阅读完整的文档here
final Promise<File> filePromise = WS.url(url).get().map(
new Function<WSResponse, File>() {
public File apply(WSResponse response) throws Throwable {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = response.getBodyAsStream();
// write the inputStream to a File
final File file = new File("/tmp/response.txt");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
return file;
} catch (IOException e) {
throw e;
} finally {
if (inputStream != null) {inputStream.close();}
if (outputStream != null) {outputStream.close();}
}
}
}
);
网址是:
String url = "http://www.google.ru/intl/en_com/images/logo_plain.png"
这是大文件播放文档中的建议:
*
当您下载大型文件或文档时,WS允许您 将响应主体作为InputStream获取,以便您可以处理数据 无需立即将整个内容加载到内存中。
*
答案 1 :(得分:1)
与上述答案几乎相同,然后是一些......
路由: POST / testFile &#39;控制器的位置在这里&#39;
请求正文内容:{"url":"http://www.google.ru/intl/en_com/images/logo_plain.png"}
控制器(使用JavaWS Processing large responses中的代码):
public static Promise<Result> saveFile() {
//you send the url in the request body in order to avoid complications with encoding
final JsonNode body = request().body().asJson();
// use new URL() to validate... not including it for brevity
final String url = body.get("url").asText();
//this one's copy/paste from Play Framework's docs
final Promise<File> filePromise = WS.url(url).get().map(response -> {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = response.getBodyAsStream();
final File file = new File("/temp/image");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
return file;
} catch (IOException e) {
throw e;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}); // copy/paste ended
return filePromise.map(file -> (Result) ok(file.getName() + " saved!")).recover(
t -> (Result) internalServerError("error -> " + t.getMessage()));
}
那就是......
为了在上传阶段之后提供文件,您可以使用此答案(我发誓我不推销自己......): static asset serving from absolute path in play framework 2.3.x