Java 从Resteasy服务器返回文件
嗨,我想从resteasy服务器返回一个文件。为此,我在客户端有一个链接,它使用ajax调用rest服务。我想返回rest服务中的文件。我尝试了这两段代码,但都没有按我所希望的那样工作Java 从Resteasy服务器返回文件,java,rest,file-io,resteasy,java-io,Java,Rest,File Io,Resteasy,Java Io,嗨,我想从resteasy服务器返回一个文件。为此,我在客户端有一个链接,它使用ajax调用rest服务。我想返回rest服务中的文件。我尝试了这两段代码,但都没有按我所希望的那样工作 @POST @Path("/exportContacts") public Response exportContacts(@Context HttpServletRequest request, @QueryParam("alt") String alt) throws IOExcep
@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();
}
当我从firebug控制台进行检查时,这两段代码都编写了“镇静BaSAR”来响应ajax调用。然而,我想返回“镇静BaSAR”作为一个文件。我该怎么做
提前谢谢。有两种方法 第一个-返回StreamingOutput Instance
@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();
}
您可以返回FILESIZEADING Content LENGTHE头,如下例所示:
return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition", "attachment; filename=\"temp.csv\"").header("Content-Length", getFileSize()).build();
但如果您不想返回StreamingOutput实例,还有其他选择
第二个-将inputstream定义为实体响应
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download() {
InputStream is = getYourInputStream();
return Response.code(200).entity(is).build();
}
您最终找到了解决方案吗?我如何返回名为UTF-8的文件?
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download() {
InputStream is = getYourInputStream();
return Response.code(200).entity(is).build();
}