java如何使用Jetty HTTP客户端和MultiPartContentProvider上载BuffereImage?
码头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(我会通过一个作业调用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 楼答案
您是否尝试在
multipart.addFilePart()
中使用OutputStreamContentProvider
而不是PathContentProvider
见https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/client/util/OutputStreamContentProvider.html
然后您可以使用
ImageIO.write(image, "png", outputStreamContentProvider);
例如: