文件下載 struts2文件下載 struts2註解

1、配置文件方式下載文件:

這種方式,網上有很多例子,我沒有試過,我用的是註解方式。


2、註解方式下載文件:
沒有上傳工程,直接附上代碼。

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
* 文件下載類
*
* @author 張國明 [email protected]
* @version 2012-11-29 上午10:34
*/
@ParentPackage("struts-default")
@Namespace("/test")
@ResultPath(value = "/")
@Results({
@Result(params = {
"contentType", "application/octet-stream",
"inputName", "inputStream",
"contentDisposition", "attachment;filename=\"${fileName}\"",
"bufferSize", "4096"},
name = "download", type = "stream")
})
public class DownloadAction extends ActionSupport {
/**
* 下載文檔,下載問價的訪問入口方法
*
* @return resultName
*/
public String testDownload() {
// 返回 @Result 註解中的 name 值
return "download";
}


/**
* 獲取下載讀入流 必須要有方法
* 在 @Result 註解的參數 params 中, key 爲 "inputName" 所對應的 value "inputStream";
* value "inputStream" ,決定該方法名爲getInputStream;
* 如果 value 的值爲 hello ,則該方法名爲 getHello;
* @return InputStream
*/
public InputStream getInputStream() {
String filePath = "E:\\works_eclipse\\四.jpg";
try {
setFileName(new String("張國明測試 圖片.jpg".getBytes(), "iso8859-1") );
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 這種方式取到的流爲null,原因不詳,所以直接 new FileInputStream
// return ServletActionContext.getServletContext().getResourceAsStream(filePath);
try {
return new FileInputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}

/**
* 下載文件的名稱,用於動態獲取下載文件的名稱(可選,即下載的文件名可以寫死在@Result的params參數中,但是沒有人會這麼傻。)
* 在 @Result 註解的參數 params 中通過 ${fileName} 來獲取該屬性 fileName 的值;
* 和EL表達式的取值方式類似,呵呵;
*/
private String fileName;

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章