Servlet - 强制覆盖下载的文件

发布于 2024-12-22 05:05:28 字数 812 浏览 1 评论 0原文

如何更改此代码以强制覆盖驱动器上保存的现有先前打开的文件?它是用于在客户端打开 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

べ映画 2024-12-29 05:05:28

无法控制它。

这取决于客户端的操作系统文件系统实现

You can't control that.

That is dependent on client's OS file system implementation

哑剧 2024-12-29 05:05:28

最好的方法是配置客户端浏览器询问是否覆盖,例如在 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:
enter image description here

To my knowledge asking to overwrite is the default behavior in Opera.

安稳善良 2024-12-29 05:05:28

在写入之前检查给定文件是否存在?
使用文件 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文