先看action类。
package actions;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileDownAction extends ActionSupport {
//读取下载文件的目录
private String inputPath;
//下载文件的文件名
private String fileName;
//读取下载文件的输入流
private InputStream inputStream;
//下载文件的类型
private String ContentType;
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public String getFileName() throws UnsupportedEncodingException {
fileName=URLEncoder.encode(fileName, "utf-8");
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getContentType() {
return ContentType;
}
public void setContentType(String contentType) {
ContentType = contentType;
}
public InputStream getInputStream() throws FileNotFoundException{
String path=ServletActionContext.getServletContext().getRealPath(inputPath);
return new BufferedInputStream(new FileInputStream(path+"\\"+fileName));
}
public String execute(){
return SUCCESS;
}
}
一个简单的jsp页面:
<a href="download.action">下载</a>
action的配置
<action name="download" class="actions.FileDownAction" method="execute">
<param name="inputPath">/image</param>
<param name="fileName">图片001.jpg</param>
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">
attachment;filename="${fileName}"
</param>
<param name="bufferSize">4000</param>
</result>
</action>
这里至少要配置两个:inputName,contentDisposition。
当然了,若图片的名字是中文,要做乱码处理。
public String getFileName() throws UnsupportedEncodingException {
fileName=URLEncoder.encode(fileName, "utf-8");
return fileName;
}