您的位置:首页 > 编程语言 > Java开发

struts2文件下载

2015-11-06 17:42 369 查看
struts2文件下载不需要链接到另一个jsp页面,故只需要一个超链接和一个处理文件下载的action类即可。

下面来看struts2文件下载的具体步骤和细节。

这是一个jsp页面的超链接,负责链接到服务器的文件流。

<a href="testDownload">Down Load</a>


在看action类的内容前有必要了解一下struts2文件下载的几个相关的文件属性

contentType 【结果类型】 默认值是 default =
text/plain


contentLength 下载的文件的长度

contentDisposition 设定Content-Disposition响应头,该响应头指定接应是一个文件下载类型,一般取值为
attachment;filename="document.pdf".

inputName 指定文件输入流的getter定义的那个属性的名字,默认为
inputStream


bufferSize 缓存大小,默认为
1024


allowCaching 是否允许使用缓存 默认为true

contentCharSet 指定下载的字符集

这几个属性都可以在struts.xml中定义或者在action里面以get的方法提供。

下面来看action类的内容。

package com.mxf.action;

import java.io.FileInputStream;
import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class Download extends ActionSupport {

/**
*
*/
private static final long serialVersionUID = 1L;

private String contentType;
private long contentLength;
private String contentDisposition ;
private InputStream inputStream;

public String getContentType() {
return contentType;
}

public void setContentType(String contentType) {
this.contentType = contentType;
}

public long getContentLength() {
return contentLength;
}

public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}

public String getContentDisposition() {
return contentDisposition;
}

public void setContentDisposition(String contentDisposition) {
this.contentDisposition = contentDisposition;
}

public InputStream getInputStream() {
return inputStream;
}

public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}

@Override
public String execute() throws Exception {
contentType = "text/html";//指定接收的文件类型为html
contentDisposition = "attachment;filename=iterator.html";
ServletContext servletContext = ServletActionContext.getServletContext();
String fileName = servletContext.getRealPath("/files/iterator.html");//项目webcontent下files文件夹下的<span style="font-family: Arial, Helvetica, sans-serif;">iterator.html</span>

inputStream = new FileInputStream(fileName);
contentLength = inputStream.available();
return SUCCESS;
}

}


上面的action分别声明了这几个属性

<span style="white-space:pre">	</span>private String contentType;
private long contentLength;
private String contentDisposition ;
private InputStream inputStream;


这表示动态生成

下面来看struts.xml的配置

<span style="white-space:pre">		</span><action name="testDownload" class="com.mxf.action.Download">
<result<span style="background-color: rgb(255, 0, 0);"> type="stream"</span>>
<param name="bufferSize">2048</param>
</result>
</action>


标红的地方必须注意:该处的type值必须为stream,不然没办法struts2框架的文件下载功能
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: