1、首先先写一个jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/csdn/Down!execute.action">下载a.jpg</a>
</body>
</html>
2、写DownAction类
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.activation.MimetypesFileTypeMap;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownAction extends ActionSupport {
//下载流对象
private InputStream inputStream;
//声明文件的类型
private String type;
//下载文件的名称
private String fileName;
//获取文件类型
public String getType() {
return type;
}
public String getFileName() {
return fileName;
}
/**
* 返回到页面中
* @return
*/
public InputStream getInputStream() {
return inputStream;
}
@Override
public String execute() throws Exception {
//获取web的真实路径地址
String realPath = ServletActionContext.getServletContext().getRealPath("/resource/类型转换测试.txt");
//获取下载的文件
File file = new File(realPath);
//获取下载文件的名称 ,简单的说了说!
fileName = new String(file.getName().getBytes(),"ISO8859-1");
//获取文件的类型
type=new MimetypesFileTypeMap().getContentType(file);
//转换程下载的流对象
inputStream = new FileInputStream(file);
//返回结果
return SUCCESS;
}
}
3、进行struts.xml配置
<package name="hbsi" extends="json-default" namespace="/csdn">
<action name="*/*" class="www.change.tm.action.{1}Action"
method="{2}">
<result name="success" type="stream">
<param name="contentType">${type}</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename=${fileName}</param>
<param name="bufferSize">1024</param>
</result>
</action>
</package>