下载 sdk struts java

<action name="sdkDownload" class="com.curiousby.sdkDownload">
			<!-- result的Type必须为stream -->
			<result name="success"  type="stream">
				<param name="contentType">
					application/octet-stream;charset=ISO-8859-1
				</param>
				<param name="contentDisposition">attachment;fileName="${fileName}"</param>
				<param name="inputName">downloadFile</param>
			</result>
		</action>
public class sdkDownload extends ActionSupport {

	private static final long serialVersionUID = -3000992581173343335L;
	private static Logger logger = Logger.getLogger(sdkDownload.class);
	private String fileName;
	private String realPath;

	/*
	 * @getFileName 此方法对应的是struts.xml文件中的: <param
	 * name="contentDisposition">attachment;filename="${fileName}"</param>
	 * 这个属性设置的是下载工具下载文件时显示的文件名, 要想正确的显示中文文件名,我们需要对fileName再次编码
	 * 否则中文名文件将出现乱码,或无法下载的情况
	 */
	public String getFileName() throws UnsupportedEncodingException {
		fileName = new String(fileName.getBytes(), "ISO-8859-1");
		return fileName;
	}

	public void setFileName() {
		String fname = ServletActionContext.getRequest().getParameter(
				"fileName");
		try {
			fname = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.fileName = fname;
	}

	public InputStream getDownloadFile() {
		this.setFileName();
		String name = ServletActionContext.getRequest().getParameter("name");
		try {
			name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		realPath = "/"+"download"+"/" + "/" + name;
		return ServletActionContext.getServletContext().getResourceAsStream(realPath);
	}
	

	//sdk的下载目前不涉及到控制权限
	@Override
	public String execute() throws Exception {
		logger.info("excute");
		
		//get fileName fisrt
		this.setFileName();
		String name = ServletActionContext.getRequest().getParameter("name");
		try {
			name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		realPath = "/"+"download"+"/" + "/" + name;
		
		// 文件下载目录路径  
		String downloadDir = ServletActionContext.getServletContext().getRealPath("/download");  
		// 文件下载路径 
		String downloadFile = ServletActionContext.getServletContext().getRealPath(realPath);
		java.io.File file = new java.io.File(downloadFile);  
		downloadFile = file.getCanonicalPath();// 真实文件路径,去掉里面的..等信息 
		// 发现企图下载不在 /download 下的文件, 就显示空内容 
		if(!downloadFile.startsWith(downloadDir))
		{  
			//放置修改路径下载web.xml文件
			//return  error
			return null; 
		}
		return SUCCESS;
	}
}
	<a class="versionTitleA" href="<%=request.getContextPath()%>/user/sdkDownload?name=air_ios_sdk.zip&fileName=air_ios_sdk.zip">iOS 版</a>
       							

  

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。



 
 
 谢谢您的赞助,我会做的更好!

猜你喜欢

转载自knight-black-bob.iteye.com/blog/2243514