Returning a file from a Resteasy server

Hi, I wanted to return the file from the resteasy server. For this purpose, I have a client side link that invokes the rest service using ajax. I want to return the file to the recreation service. I tried these two blocks of code, but both of them did not work the way I wanted.

@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; } 

When I checked from the firebug console, both of these code blocks wrote "Sedat BaSAR" in response to an ajax call. However, I want to return "Sedat BaSAR" as a file. How can i do this?

Thanks in advance.

+7
source share
1 answer

There are two ways to do this.

1st - returns stream 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(); } 

You can return the file size by adding the Content-Length header, in the following example:

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

But if you do not want to return an instance of StreamingOutput, there is another option.

2nd - Define the input stream as the response of the object.

 @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response download() { InputStream is = getYourInputStream(); return Response.code(200).entity(is).build(); } 
+12
source

All Articles