struts2文件下载

struts配置文件


<!-- 文件stream方式下载 -->
		<action name="DownloadAction" class="action.DownLoadAction" method="execute">
			<!-- 以stream二进制流的方式打开 -->
			<result name="success" type="stream">
				<!-- 指明文件的下载类型 -->
				<!-- 动态文件下载的,事先并不知道未来的文件类型,那么我们可以把它的值设置成为:application/octet-stream;charset=ISO8859-1 ,注意一定要加入charset,否则某些时候会导致下载的文件出错; -->
				<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
				<!-- 指明如果取得需要下载文件的InputStream输入流 -->
				<param name="inputName">imageStream</param>
				<!-- 指明让浏览器以下载框的方式打开 -->
				<!-- <param name="contentDisposition">attachment;filename="building.jpg"</param> -->
				<param name="contentDisposition">attachment;filename=${fileName}</param>
				<!-- 指明下载文件时的字符数组byte[]大小 -->
				<param name="bufferSize">1024</param>
			</result>
		</action>

action类

public void setFileName(String fileName) throws Exception {
        if(ServletActionContext.getRequest().getMethod().equals("GET")){
            byte[] bytes = fileName.getBytes("ISO8859-1");
            fileName=new String(bytes,"utf-8");
        }
        this.fileName = fileName;
    }
	
    public String getFileName() throws Exception {
        return URLEncoder.encode(fileName, "utf-8");
    }
    
    public InputStream getImageStream() throws Exception {
		String path = System.getProperty("user.dir") + File.separator + "src"+File.separator+"main"
				+File.separator+"webapp"+File.separator+"images"+File.separator+fileName;
		File file = new File(path);
		InputStream inputStream = new FileInputStream(file);
        return inputStream;
    }

触发链接时传递filename

<a href="/download/DownloadAction.action?fileName=${fileName }">文件下载</a>


你可能感兴趣的:(struts2文件下载)