gpt4 book ai didi

java - 启用通过resteasy将图像作为Fileoutputstream发送

转载 作者:太空宇宙 更新时间:2023-11-04 06:06:56 25 4
gpt4 key购买 nike

在我的服务器端,我有一个图像将通过其余方式发送到客户端发送后,图像应被删除。

因此图像将被复制到文件输出流上,我将文件输出流发送到客户端,然后删除图像。

我使用以下代码:

@GET
@Path("/get_image")
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
public Response getImage(){

.......

File image = new File("myimage.png");
FileOutputStream oos = new FileOutputStream("imageToSend.png");
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(image);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}

ResponseBuilder response = Response.ok(oos);
response.header("Content-Disposition",
"attachment; filename=image.png");
oos.close();
is.close();

image.delete();

return response.build();
}
}

但是当我执行 getImage 方法时,我发现了这个错误

org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure: Could not find MessageBodyWriter for response object of type: java.io.FileOutputStream of media type: application/octet-stream
at org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:67)
at org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:411)

如果有人知道这个问题的原因......

亲切的问候

最佳答案

您应该仅使用 InputStream 作为响应正文(RESTeasy 将为您进行写入),或者您可以使用 StreamingOutput 将数据直接写入响应流。例如

StreamingOutput output = new StreamingOutput() {
@Override
public void write(OutputStream out) {
InputStream is = new FileInputStream(image);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
is.close();
}
}

ResponseBuilder response = Response.ok(output);

使用返回InputStream 可能会更容易。它在底层做了几乎相同的事情,就像使用上面的 StreamingOutput 一样。我过去遇到的一件奇怪的事情是在尝试返回InputStream 时处理大文件。使用StreamingOutput,它似乎工作得更好。

关于java - 启用通过resteasy将图像作为Fileoutputstream发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31203248/

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