=============================struts 文件下载 ==================================
步骤一: JSP页面
<a href="download.action?fileName=IMG_0443.JPG">点击此处下载图片</a>
步骤二: Action页面
package org.zm.action;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownLoadAction extends ActionSupport{
//读取下载文件的目录
private String inputPath;
//下载文件的文件名
private String fileName;
//读取下载文件的输入流
private InputStream inputStream;
//下载文件的类型
private String conetntType;
//创建InputStream输入流
public InputStream getInputStream() throws FileNotFoundException{
String path=ServletActionContext.getServletContext().
getRealPath(inputPath);
return new BufferedInputStream(new FileInputStream(path+"\\"+
fileName));
}
@Override
public String execute() {
return SUCCESS;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getConetntType() {
return conetntType;
}
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public void setConetntType(String conetntType) {
this.conetntType = conetntType;
}
}
步骤三: Struts.xml文件
<action name="download" class="org.zm.action.DownLoadAction">
<param name="inputPath">/upload</param>
<result name="success" type="stream">
<param name="contentType">image/pjpeg</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">4096</param>
</result>
</action>
提示: Stream结果类型
contentType: 设置发送到浏览器的MIME类型
contentLength: 文件大小
contentDisposition: 设置响应的HTTP头信息的Content-Disposition参数的值
inputName: 指定Action提供的inputStream类型的属性名称
bufferSize:设置读取和下载文件时缓冲区的大小
struts.xml文件和Action 这两处位置的变量名称一定要正确。