摘要:Struts2提供了stream结果类型,该结果类型是专门用于支持文件下载功能的。配置stream类型的结果需要指定以下4个属性。 contentType:指定被下载文件的文件类型 inputName:指定被下载文件的入口输入流 contentDisposition:指定下载的文件名 bufferSize:指定下载文件时的缓冲大小 struts2文件下载示例:1.处理文件下载的Action:?123456789101112131415161718192021222324/**&
Struts2提供了stream结果类型,该结果类型是专门用于支持文件下载功能的。配置stream类型的结果需要指定以下4个属性。
contentType:指定被下载文件的文件类型
inputName:指定被下载文件的入口输入流
contentDisposition:指定下载的文件名
bufferSize:指定下载文件时的缓冲大小
struts2文件下载示例:
1.处理文件下载的Action:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /**
* Description:Struts2控制文件下载
* Author: Eleven
* Date: 2018/1/24 10:39
*/
public class FileAction extends ActionSupport{
private InputStream targetFile;
public String download(){
String path = "/WEB-INF/images/lib.zip" ;
targetFile = ServletActionContext.getServletContext().getResourceAsStream(path);
return SUCCESS;
}
public InputStream getTargetFile() {
return targetFile;
}
}
|
文件下载,首先得要有被下载的文件资源,这里我将被下载文件放在了项目的WEB-INF/images的路径下面,可根据自己的需求来,然后直接用ServletContext提供的getResourceAsStream()方法返回指定文件对应的输入流。
2.配置struts.xml
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <? xml version = "1.0" encoding = "UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
< struts >
< constant name = "struts.enable.DynamicMethodInvocation" value = "false" />
< constant name = "struts.devMode" value = "true" />
< package name = "default" namespace = "/" extends = "struts-default" >
< action name = "file_*" class = "eleven.action.FileAction" method = "{1}" >
< result type = "stream" >
< param name = "contentType" >application/zip</ param >
< param name = "inputName" >targetFile</ param >
< param name = "contentDisposition" >filename="aaa.zip"</ param >
< param name = "bufferSize" >4096</ param >
</ result >
</ action >
</ package >
</ struts >
|
在浏览器地址栏中输入对应的文件下载的访问路径,如http://localhost:8080/demo/file_download,即可下载文件了。\
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。