struts2注解方式文件下载

@Namespace("/")
@ParentPackage("default")
public class ManageNewAction extends BaseAction{
	private String attachname;//下载文件的名字
	
	private InputStream attachstream;//文件读取流对象
	
	//下载文件,目前只有下载语音
     @Action(value = "/manage_downFile",
	results = {@Result(name = "success", type = "stream", 
			  params = {
                  "contentType", "application/octet-stream",
                  "inputName", "attachstream",
                  "contentDisposition", "attachment;filename=\"${attachname}\"",
                  "bufferSize", "4096"
	})})
	public String manage_downFile() throws IOException{
		String path = ServletActionContext.getServletContext().getRealPath("/data/voice/user/2_210_1499774129.mp3");
		System.out.println(path);
		String filePath = paramString("filePath");
		filePath = Global.serverDir+filePath;
		filePath = Global.serverDir+"/data/voice/user/2_210_1499774129.mp3";
		attachstream = new FileInputStream(filePath);
		attachname  = "2_210_1499774129.mp3";
		return SUCCESS;
	}
	
	public InputStream getAttachstream() {
		return attachstream;
	}




	public void setAttachstream(InputStream attachstream) {
		this.attachstream = attachstream;
	}




	public String getAttachname() {
		return attachname;
	}




	public void setAttachname(String attachname) {
		this.attachname = attachname;
	}
}

参数说明:

type = "stream",这里的type一定要等于stream;

对params的几个参数的解释:

"contentType", "application/octet-stream" : 文件格式;

"inputName", "attachstream" :获取文件的方法名;这里的attachstream需要和action里的attachstream对应,类型就是InputStream;

"contentDisposition", "attachment;filename=\"${attachname}\"":文件内容(显示的)属性,

这里的filename=\"${attachname}\" :下载之后的文件名;这里需要在action里定义一个变量,去获取下载文件的文件名,包括后缀,例如:下载的文件为**/**/upload/test.jpg,那么需要定义一个变量attachname,变量名一定要对应,然后,attachname = test.jsp;

"bufferSize", "4096" :限定下载文件 缓冲区的值;




你可能感兴趣的:(javaee,java)