Servlet - 强制覆盖下载的文件
如何更改此代码以强制覆盖驱动器上保存的现有先前打开的文件?它是用于在客户端打开 pdf 文件的 servlet 的一部分。
response.reset();
response.setContentType("application/pdf");
response.setContentLength(file.length());
response.setHeader("Content-disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try
{
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0)
{
output.write(buffer, 0, length);
}
}
finally
{
close(output);
close(input);
}
打开文件的每个下一个副本都有一个新索引,例如 test.pdf、test(1).pdf 等
How to change this code to force overwrite existing previously opened file saved on drive? It's part of servlet for opening pdf files on client side.
response.reset();
response.setContentType("application/pdf");
response.setContentLength(file.length());
response.setHeader("Content-disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try
{
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0)
{
output.write(buffer, 0, length);
}
}
finally
{
close(output);
close(input);
}
Each next copy of opened file has a new index, e.g. test.pdf, test(1).pdf and so on
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你无法控制它。
这取决于客户端的操作系统文件系统实现
You can't control that.
That is dependent on client's OS file system implementation
最好的方法是配置客户端浏览器询问是否覆盖,例如在 Firefox 中:
据我所知,要求覆盖是 Opera 中的默认行为。
The best you can do it to configure the client browser to ask whether to overwrite or not, for example in Firefox it is:
To my knowledge asking to overwrite is the default behavior in Opera.
在写入之前检查给定文件是否存在?
使用文件 api file.exists() 如果存在,使用文件 api file.delete() 删除给定文件并继续写入过程
before going to write check whether the given file is exist or not?
using file api file.exists() if it exists, delete given file using file api file.delete() and continue with writing process