我们怎么能使用来自angularjs的get请求下载文件,其中rest api以java为中间层,在java层数据根据api中的查询参数作为输入流。 请帮忙 流程是这样的:
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
答案 0 :(得分:0)
以下是使用StreamingOutput类使用JAX-RS Jersey编写流式REST API的源代码。
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();
}
}
注意:如果您点击了该网址,您的浏览器会显示警告以下载该文件。用于保存PDF文件的文件名将是您在Response.header()
方法中设置的文件。