从Resteasy服务器返回文件

Sed*_*şar 10 java rest file-io resteasy java-io

嗨,我想从resteasy服务器返回一个文件.为此,我在客户端有一个链接,它使用ajax调用rest服务.我想在休息服务中返回该文件.我尝试了这两个代码块,但两个都没有按照我的要求工作.

    @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();
    }
Run Code Online (Sandbox Code Playgroud)

.

@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;
}
Run Code Online (Sandbox Code Playgroud)

当我从firebug控制台检查时,这两个代码块都写了"Sedat BaSAR"来响应ajax调用.但是,我想将"Sedat BaSAR"作为文件返回.我怎样才能做到这一点?

提前致谢.

小智 16

有两种方法可以实现.

1st - 返回StreamingOutput instace.

@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();
}
Run Code Online (Sandbox Code Playgroud)

您可以返回添加Content-Length标头的filesize,如下例所示:

return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition", "attachment; filename=\"temp.csv\"").header("Content-Length", getFileSize()).build();
Run Code Online (Sandbox Code Playgroud)

但是如果你不想返回StreamingOutput实例,还有其他选择.

第二 - 将输入流定义为实体响应.

@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download() {
    InputStream is = getYourInputStream();

    return Response.code(200).entity(is).build();
}
Run Code Online (Sandbox Code Playgroud)