1. 程式人生 > >jquery struts2 檔案下載

jquery struts2 檔案下載

不多說,直接上程式碼

<a href="#" id="downLoad" onClick="downLoad(fName);">'下載'</a>

<script>
//實現檔案下載
       jQuery.download = function(url, data, method) {
		// 獲取url和data
		if (url && data) {
			// data 是 string 或者 array/object
			data = typeof data == 'string' ? data : jQuery.param(data);
			// 把引數組裝成 form的  input
			var inputs = '';
			jQuery.each(data.split('&'), function() {
				var pair = this.split('=');
				inputs += '<input type="hidden" name="' + pair[0] + '" value="'+ pair[1] + '" />';
			});
			// request傳送請求
			jQuery(
					'<form action="' + url + '" method="' + (method || 'post')
							+ '">' + inputs + '</form>').appendTo('body')
					.submit().remove();
		};
	};
			//下載附件
			function downLoad(fileName) {
				$.download("../action/downLoadFIle.a","paramFileName="+fileName,"post");
			}
		</script>

java程式碼

package cn.okaysoft.cfs.action.pei;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DanganDownFileAction extends ActionSupport{
	private String paramFileName; // 要下載的檔名

	public void setParamFileName(String paramFileName) {
		this.paramFileName = paramFileName;
	}

	public String getParamFileName() {
		return paramFileName;
	}

	// struts檔案下載
	public InputStream getDownloadFile() throws Exception {
		String readPath = ServletActionContext.getServletContext().getRealPath(
				"");
		String realName = paramFileName;
		readPath = readPath + "\\compilation\\" + realName; // 讀檔案路徑
		// 解解亂碼
		paramFileName = new String(paramFileName.getBytes("gbk"), "ISO-8859-1");
		String realPath="/compilation/"+realName;
		try {
			InputStream in= ServletActionContext.getServletContext().getResourceAsStream(realPath);
	     return in;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
			
		}
	}
	 @Override  
	public String execute() throws Exception {
		return SUCCESS;
	}
}

//struts2配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
	<package name="dangan-fileDown" extends="struts-default"
		namespace="/action">
		<action name="downLoadFIle" class="cn.okaysoft.cfs.action.pei.DanganDownFileAction">
			<result name="success" type="stream">
				<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
				<param name="contentDisposition">attachment;fileName="${paramFileName}"</param>
				<param name="inputName">downloadFile</param>
				<param name="bufferSize">1024</param>
			</result>
		</action>

	</package>

</struts>