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

How to upload a BufferedImage using Jetty HTTP client and MultiPartContentProvider?

使用 Jetty 9.4.21.v20190926 我 运行 自定义 servlet(WAR 文件),它能够生成像这样的图像:

通过以下代码:

@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 or maybe 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);
 }