struts2文件下载


    Struts2文件下载
目录:
struts2文件下载_第1张图片

struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <package name="down" namespace="/downLoad" extends="struts-default">
     <action name="liuDownLoad" class="liu.chao.action.LiuDownLoad">
       <result name="success" type="stream">
           <!-- 下载的文件类型 -->
           <param name="contentType">application/octet-stream</param>
           <!-- 下载的文件处理方式 -->
           <param name="contentDisposition">attachment;fileName="${fileName}"</param>
           <!-- 下载文件的输出流对应于Action里面的getInputStream()方法 -->
           <param name="inputName">inputStream</param>
       </result>
     </action>
  </package>
</struts>

Action:
package liu.chao.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class LiuDownLoad extends ActionSupport {
   
	private String filePath;//要下载文件的目录 如:images
    private String fileName;//要下载的文件名称 如:003.png
    public String getFilePath() {
		return filePath;
	}
	
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
    
    public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	
	public InputStream getInputStream()throws Exception{
		 
		   String path=ServletActionContext.getServletContext().getRealPath(filePath);
		   File file=new File(path,fileName);
		   InputStream input=new FileInputStream(file);
		   return input;
	}	
	
 
	
	public String execute(){
		 
		 return SUCCESS;
	 }
	
	
}

前台代码:
    <form action="downLoad/liuDownLoad.action" name="form" method="post">
      文件要下载目录(eg:images):<input type="text" name="filePath" id="003"/></br>
      文件名称(eg:003.png):<input type="text" name="fileName" id="004"/>
      <input type="submit" value="下载"/>
    </form>

运行效果:
struts2文件下载_第2张图片

你可能感兴趣的:(struts)