gpt4 book ai didi

java - 如何使用 Jetty HTTP 客户端和 MultiPartContentProvider 上传 BufferedImage?

转载 作者:行者123 更新时间:2023-12-02 09:20:43 28 4
gpt4 key购买 nike

使用 Jetty 9.4.21.v20190926,我运行一个自定义 servlet(一个 WAR 文件),它能够生成如下所示的图像:

generated image

通过以下代码:

@Override
protected void doGet(HttpServletRequest httpReq, HttpServletResponse httpResp) throws ServletException, IOException {
BufferedImage image = new BufferedImage(512, 512, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// ...drawing code skipped here...
g.dispose();
httpResp.setStatus(HttpServletResponse.SC_OK);
httpResp.setContentType("image/png");
ImageIO.write(image, "png", httpResp.getOutputStream());
}

这效果很好,现在我想向我的 servlet 添加另一个功能:uploading the same image by HTTP POST to another website (我将通过每小时的 cronjob 调用我的 servlet 上的 URL 来触发上传)。

我明白,我应该使用MultiPartContentProvider和以下代码:

MultiPartContentProvider multiPart = new MultiPartContentProvider();
multiPart.addFilePart("attached_media", "img.png", new PathContentProvider(Paths.get("/tmp/img.png")), null);
multiPart.close();

但是我不想将生成的图像保存为临时文件。

相反,我想使用BytesContentProvider或者也许InputStreamContentProvider …但是如何通过 ImageIO.write() 调用将它们结合起来?

最佳答案

您是否尝试过在 multipart.addFilePart() 中使用 OutputStreamContentProvider 而不是 PathContentProvider

参见https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/client/util/OutputStreamContentProvider.html

然后你就可以使用ImageIO.write(image, "png", outputStreamContentProvider);

示例:

HttpClient httpClient = ...;

// the output for the image data
OutputStreamContentProvider content = new OutputStreamContentProvider();
MultiPartContentProvider multiPart = new MultiPartContentProvider();
multiPart.addFilePart("attached_media", "img.png", content, null);
multiPart.close();
// Use try-with-resources to autoclose the output stream
try (OutputStream output = content.getOutputStream())
{
httpClient.newRequest("localhost", 8080)
.content(multipart)
.send(new Response.CompleteListener()
{
@Override
public void onComplete(Result result)
{
// Your logic here
}
});

// At a later time...
ImageIO.write(image, "png", output);
}

关于java - 如何使用 Jetty HTTP 客户端和 MultiPartContentProvider 上传 BufferedImage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713134/

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