Возврат файла с сервера Resteasy - PullRequest
10 голосов
/ 16 ноября 2011

Привет, я хотел вернуть файл с сервера 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» в виде файла. Как я могу это сделать?

Заранее спасибо.

1 Ответ

16 голосов
/ 24 апреля 2014

Есть два пути к этому.

1-й - возвращает объект 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, есть другой вариант.

2nd - определение входного потока в качестве ответа объекта.

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

    return Response.code(200).entity(is).build();
}
...