我使用的是泽西服务器,我希望端点根据参数重定向到文件下载。
我对以下功能有困难:
@GET
@Path("/get/{id}/{chunk}")
public Response getDescription(@PathParam("id") String id, @PathParam("chunk") String chunk) {
{
StreamingOutput fileStream = new StreamingOutput()
{
@Override
public void write(java.io.OutputStream output, String id) throws IOException, WebApplicationException
{
try
{
if (Objects.equals(chunk, new String("init"))) {
java.nio.file.Path path = Paths.get("src/main/uploads/example/frame_init.pdf");
}
else {
java.nio.file.Path path = Paths.get("src/main/uploads/example/"+ id +".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();
}
将参数传递给函数write时遇到问题。我有端点的参数id和chunk,但我不能在write方法中使用它,因为它实现了StreamingOutput()。
我该如何处理?谢谢
答案 0 :(得分:1)
对于java,final关键字应解决您的问题。
更新代码;
@GET
@Path("/get/{id}/{chunk}")
public Response getDescription(@PathParam("id") final String id, @PathParam("chunk") final String chunk) {
{
StreamingOutput fileStream = new StreamingOutput()
{
@Override
public void write(java.io.OutputStream output, String id2) throws IOException, WebApplicationException
{
try
{
if (Objects.equals(chunk, new String("init"))) {
java.nio.file.Path path = Paths.get("src/main/uploads/example/frame_init.pdf");
}
else {
java.nio.file.Path path = Paths.get("src/main/uploads/example/"+ id2 +".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();
}