struts2下载
java代码
1 package com.web.action; 2 3 import java.io.InputStream; 4 import java.io.UnsupportedEncodingException; 5 import org.apache.struts2.ServletActionContext; 6 7 import com.opensymphony.xwork2.ActionSupport; 8 9 public class FileDownload2Action extends ActionSupport{ 10 private String fileName; 11 12 public String getFileName() { 13 return fileName; 14 } 15 16 public void setFileName(String fileName) { 17 this.fileName = fileName; 18 } 19 public InputStream getInputStream(){ 20 //文件路径 21 String url="/downdir/Linux常用命令全集.CHM"; 22 try { 23 //下载文件名 24 fileName=new String("Linux常用命令全集.CHM".getBytes("GBK"),"ISO8859_1"); 25 } catch (UnsupportedEncodingException e) { 26 // TODO Auto-generated catch block 27 e.printStackTrace(); 28 } 29 return ServletActionContext.getServletContext().getResourceAsStream(url); 30 } 31 32 @Override 33 public String execute() throws Exception { 34 return "success"; 35 } 36 }
struts.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4 "http://struts.apache.org/dtds/struts-2.3.dtd"> 5 <struts> 6 <constant name="struts.i18n.encoding" value="GBK"></constant> 7 <!-- 返回的结果是流 inputname的参数是action里面的一个get+方法名 8 --> 9 <package name="default" extends="struts-default"> 10 <action name="fileDownload2" class="com.web.action.FileDownload2Action"> 11 <result type="stream"> 12 <param name="inputName">inputStream</param> 13 <param name="contentDisposition">filename=${fileName}</param> 14 </result> 15 </action> 16 </package> 17 </struts>
注意:struts2下载前端页面必须是a标签