有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Jetty HTTP客户端和MultiPartContentProvider上载BuffereImage?

码头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(我会通过一个作业调用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()呼叫结婚呢


共 (1) 个答案

  1. # 1 楼答案

    您是否尝试在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);
     }