简单的下载功能实现(struts2)
简单的下载功能实现(struts2)1.前台页面:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%><%@ taglib prefix ="s" uri="/struts-tags"%><html> <head><script type="text/javascript"> function changeValidateCode(obj) { /*** * 获取当前的时间作为参数,无具体意义 * 每次请求需要一个不同的参数,否则可能会返回同样的验证码 * 这和浏览器的缓存机制有关系,也可以把页面设置为不缓存,这样就不用这个参数了。 */var timenow = new Date().getTime(); obj.src="randPic.action?d="+timenow; } </script> </head> <body> <form name="" action="Login"> 验证码:<s:textfield name="code"></s:textfield><img src="randPic.action" onclick="changeValidateCode(this)" title="点击图片刷新验证码"/> <br/><input type="submit" value="登陆"/><input type="reset" value="重置"/> </form> <s:a href="download/view">查看图片</s:a><br/> <s:a href="download/save">下载图片</s:a> </body></html>
<?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="image" extends="struts-default" namespace="/"> <action name="randPic" extends="struts-default" namespace="/download"> <action name="view" type="stream"> <param name="contentType">image/jpeg</param> <param name="contentDisposition">filename="picture.jpg"</param> <param name="inputName">simpleDownloadStream</param> </result> </action> <action name="save" type="stream"> <param name="contentType">application/octet-stream</param> <param name="contentDisposition">filename="picture.jpg"</param> <param name="inputName">simpleDownloadStream</param> </result> </action> </package></struts>
package com.org.momo.action;import java.io.InputStream;import javax.servlet.ServletContext;import org.apache.struts2.util.ServletContextAware;import com.opensymphony.xwork2.ActionSupport;public class SimpleFileDownloadAction extends ActionSupport implements ServletContextAware{ private static final long serialVersionUID = 620526993016670680L; private ServletContext context; public void setServletContext(ServletContext context){ this.context = context; } public InputStream getSimpleDownloadStream(){ return context.getResourceAsStream("/download/10.JPG"); } public String execute(){ return SUCCESS; }}