gpt4 book ai didi

java - Play Framework 。如何使用外部端点上传照片?

转载 作者:行者123 更新时间:2023-12-01 22:21:27 25 4
gpt4 key购买 nike

如何使用 playframework 中的 URL 上传照片?我当时是这样想的:

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);

但也许还有另一种方法。最后我必须获取文件和文件名。

Controller 示例:

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');
}

最佳答案

要获取该照片,您可以使用 play WS API,后面的代码是从处理大型响应部分中的 play 文档中提取的示例,我建议您阅读完整文档 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"

这是大文件 Play 文档中建议的:

*

When you are downloading a large file or document, WS allows you to get the response body as an InputStream so you can process the data without loading the entire content into memory at once.

*

关于java - Play Framework 。如何使用外部端点上传照片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29673393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com