你好,我想从 Resteasy 服务器返回一个文件。为此,我在客户端有一个链接,它使用 ajax 调用休息服务。我想在其余服务中返回文件。我尝试了这两段代码,但都没有按照我想要的方式工作。
@POST
@Path("/exportContacts")
public Response exportContacts(@Context HttpServletRequest request, @QueryParam("alt") String alt) throws IOException {
String sb = "Sedat BaSAR";
byte[] outputByte = sb.getBytes();
return Response
.ok(outputByte, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition","attachment; filename = temp.csv")
.build();
}
.
@POST
@Path("/exportContacts")
public Response exportContacts(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("alt") String alt) throws IOException {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=temp.csv");
ServletOutputStream out = response.getOutputStream();
try {
StringBuilder sb = new StringBuilder("Sedat BaSAR");
InputStream in =
new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
byte[] outputByte = sb.getBytes();
//copy binary contect to output stream
while (in.read(outputByte, 0, 4096) != -1) {
out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {
}
return null;
}
当我从 firebug 控制台检查时,这两个代码块都写了“Sedat BaSAR”来响应 ajax 调用。但是,我想将“Sedat BaSAR”作为文件返回。我怎样才能做到这一点?
提前致谢。
有两种方法可以实现。
第一 - 返回 StreamingOutput 实例。
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download() {
InputStream is = getYourInputStream();
StreamingOutput stream = new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
output.write(IOUtils.toByteArray(is));
}
catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition", "attachment; filename=\"temp.csv\"").build();
}
您可以添加 Content-Length 标头来返回文件大小,如下例:
return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition", "attachment; filename=\"temp.csv\"").header("Content-Length", getFileSize()).build();
但如果您不想返回 StreamingOutput 实例,还有其他选择。
第二 - 将输入流定义为实体响应。
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download() {
InputStream is = getYourInputStream();
return Response.code(200).entity(is).build();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)