使用jax-rs发送临时文件
我试图用jax-rs发送一个临时文件,并在下载完成后删除临时文件。 为此,我将InputSream子类化,以便在流关闭后得到通知。 这是我到目前为止:
@GET @Path("download/{fileName}") public Response downloadFile(@PathParam("fileName") String fileName) { InputStream inputStream = new InputStreamWithFileDeletion(new getFile(filename)); Response.ResponseBuilder response = Response.ok((Object) file); response.header("Content-Disposition", "attachment; filename="+"fileName"+".xls"); return response.build(); }
InputStreamWithFileDeletion:
public class InputStreamWithFileDeletion extends FileInputStream { File f; public InputStreamWithFileDeletion(File file) throws FileNotFoundException { super(file); f = file; } @Override public void close() throws IOException { super.close(); f.delete(); } }
不幸的是,一旦下载完成,就不会调用close()。 我错过了什么吗?
更改
Response.ResponseBuilder response = Response.ok((Object) file);
至
Response.ResponseBuilder response = Response.ok(inputStream);
根据Sven Junga的回答,我提出了这个解决方案:
Path p = Paths.get(tempFile); InputStream is = Files.newInputStream(p); Files.delete(p); return Response.ok(is).header("Content-Disposition", "attachment; filename=f.txt").build();
一旦消耗了输入流,该文件将被删除。
改变这一行
InputStream inputStream = new InputSreamWithFileDelition(new getFile(filename));
至
InputSreamWithFileDelitioninputStream = new InputSreamWithFileDelition(new getFile(filename));
确保调用好的close
方法。
然后在InputStreamWithFileDelition
类中实现AutoCloseAble
,默认情况下会调用您的overriden close方法。