Struts2.x上传和下载文件

struts2 上传文件

1)提交表单设置

   Html代码  

<form action="upload.do" method="post" enctype="multipart/form-data">  
    <table>  
        <tr>  
            <td>选择文件</td>  
            <td>  
                <input type="file" name="upload" value=""/>  
            </td>  
        </tr>  
        <tr>  
            <td><input type="submit" value="上传文件" /></td>  
        </tr>  
    </table>  
</form>  

注意enctype一定要是"multipart/form-data"

2)Action代码

public class UploadAction extends ActionSupport {

	private static final long serialVersionUID = 1224534552231961695L;

	protected final Log logger = LogFactory.getLog(getClass());
	
	private File upload;				// 上传的临时文件
	private String uploadContentType;	// 文件的类型
	private String uploadFileName;		// 文件名

	@Override
	public String execute() throws Exception {
		
		// 文件类型检查
		if (! uploadContentType.equals("application/msword")) {
			addFieldError("upload", "非法的上传文件类型");
			return INPUT;
		} 
		
		String tmpPath = ServletActionContext.getServletContext().getRealPath("tmp");
		FileUtils.copyFile(upload, new File(tmpPath, uploadFileName));		// 拷贝文件
		return SUCCESS;
	}

	// getter setter ...
}

3)配置Action strutsl.xml 
 

<!-- ... -->
<action name="upload" class="net.csdn.struts.action.UploadAction">
	<param name="allowedTypes">application/msword,text/html</param>   <!-- 注入给Action用于配置允许上传类型 -->
	<result name="success" type="dispatcher">/WEB-INF/jsp/success.jsp</result>
	<result name="input" type="dispatcher">/index.jsp</result>
</action>

struts2 下载文件

1)DownloadAction

public class DownloadAction {

	private String inputPath;

	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}

	public InputStream getTargetFile() {
		return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
	}
	
	public String execute() throws Exception {
		return "success";
	}
}


2)配置Action

<action name="download" class="net.csdn.struts.action.DownloadAction">
	<param name="inputPath">/tmp/some.doc</param>
	<result type="stream">
		<!-- 文件类型 -->
		<param name="contentType">application/msword</param>
		<!-- Action中的InputStream -->
		<param name="inputName">targetFile</param>
		<!-- 设置文件名 -->
		<param name="contentDisposition">filename="中文.doc"</param>
		<!-- 缓存大小 -->
		<param name="bufferSize">4096</param>
	</result>
</action>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值