Anuj Tomar
Anuj Tomar

Reputation: 97

How to download a CSV file by StreamingOutput

How we can can download a file using a get request from angularjs with rest api to java as middle layer and at java layer data comes as input stream on the basis of query parameter in api. Please help The flow is like so :

       request From angular controller -------get/api?name=xyz --- java --- 
       query to database for InputStream = "name=xyz using http client";
       response is in csv format itself.
       Response need to be downloaded into a file

Upvotes: 2

Views: 5199

Answers (1)

Mithun Sasidharan
Mithun Sasidharan

Reputation: 20950

Below is the source code for writing an streaming REST API using JAX-RS Jersey using StreamingOutput class.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

@Path("/download")
public class JerseyService 
{
    @GET
    @Path("/pdf")
    public Response downloadPdfFile()
    {
        StreamingOutput fileStream =  new StreamingOutput() 
        {
            @Override
            public void write(java.io.OutputStream output) throws IOException, WebApplicationException 
            {
                try
                {
                    java.nio.file.Path path = Paths.get("C:/temp/test.pdf");
                    byte[] data = Files.readAllBytes(path);
                    output.write(data);
                    output.flush();
                } 
                catch (Exception e) 
                {
                    throw new WebApplicationException("File Not Found !!");
                }
            }
        };
        return Response
                .ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition","attachment; filename = myfile.pdf")
                .build();
    }
}

Note : If you hit the URL, you will be shown alert in your browser to download the file. The filename with which PDF file will be saved, will be what you set in Response.header() method.

Upvotes: 2

Related Questions