如何下载文件而不是在浏览器中打开?

ant*_*nto 4 html javascript java spring-mvc download

我是一个新的bie,我希望文件在用户点击下载选项时下载它在浏览器中打开而不是下载选项如save as/open.Here我引用了相同的以及他们建议使用的每个地方

Response.AddHeader("Content-disposition", "attachment; filename=" + Name);
Run Code Online (Sandbox Code Playgroud)

但我不知道在哪里以及如何使用.实际上我从查询中获取了url值,返回url作为存储在arraylist中的bean的对象之一(此列表还有url的其他值).我在arraylist中的url值就像bean一样

type=.pdf
release date=12/3/08
name=hai.pdf
url=/files/en/soft/doc/docs/hai.pdf
Run Code Online (Sandbox Code Playgroud)

我在我的控制器中得到这个数组列表

ArrayList details = dao.getdetails(Bean.getNumber());
Run Code Online (Sandbox Code Playgroud)

并将此传递到视图中

Map.put("details", details);
modelView.setViewName("details_list");
modelView.addAllObjects(Map);
return modelView;
Run Code Online (Sandbox Code Playgroud)

在jsp中,我迭代了这个数组列表并像这样显示内容

Type    name            Release Date            
.txt    hai.pdf     May 21st 2012   Download

.txt    hello.txt   May 21st 2012   Download
Run Code Online (Sandbox Code Playgroud)

为了下载,我在jsp中使用了这样的

<td colspan="2" valign="top">                           
<a href="${details.Url}"/>
<img src="/images/download.gif" alt="Download" border="0" align="right"></a>
</td>
Run Code Online (Sandbox Code Playgroud)

点击下载在浏览器中打开它.我需要下载它.请帮助我如何使用或处理

response.setHeader("Content-Disposition", "attachment;");
Run Code Online (Sandbox Code Playgroud)

在哪里添加上面的我的要求或如果我也可以使用任何java脚本.请帮助我解决上述问题.

San*_*osh 5

这是一种方法:

  1. 创建一个Web 过滤器(或这种方式)
  2. 将此过滤器映射到PDF URL.
  3. 在该doFilter()方法中,设置内容下载的响应头.

示例:

public void doFilter(ServletRequest request, 
   ServletResponse response, FilterChain chain)
   throws IOException, ServletException {

          String name = request.getAttribute("filename");

           response.addHeader("Content-disposition", "attachment; filename=" + name);
           chain.doFilter(request, response);


}
Run Code Online (Sandbox Code Playgroud)

您可以将文件名设置为来自控制器类的请求属性(reqest.setAttribute())

过滤器在Java Web堆栈中非常标准.