`
zhujinguo
  • 浏览: 131011 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

通过流下载附件,使用struts2下载附件

阅读更多
1、通过流下载附件
//文件下载
	public String fileDown(){
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			String path=session.getServletContext().getRealPath("/");
			filename   = new String( filename.getBytes("ISO-8859-1") , "UTF-8");   
			
			String downname = filename.split("---")[2]; 
			String url = path+"doc/affix/"+tba.getIassistnoticeid()+"/"+filename; 
			OutputStream out = response.getOutputStream();
			response.reset();
			// 指定返回的是一个不能被客户端读取的流,必须被下载 
			response.setContentType("application/octet-stream;charset=UTF-8");
			// 添加头信息,为"文件下载/另存为"对话框指定默认文件名 
			response.setHeader("Content-disposition", "attachment; filename="+URLEncoder.encode(downname,"UTF-8")); //URLEncoder.encode转换,解除文件名乱码 
			// 添加头信息,指定文件大小,让浏览器能够显示下载进度 
			//response.addheader("content-length", url.length.tostring()); 
			FileInputStream fis=new FileInputStream(url);    
			int i=-1;
			while((i=fis.read())!=-1){//读文件
				out.write(i);         //写文件
			}
			out.flush();out.close();fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			return null;
		}
	}


2、使用struts2下载附件
//文件下载
	public String fileDown(){
		mimeType = session.getServletContext().getMimeType(filename);
        return "filedown";    
	}
	
	/**
     * 封装处理文件名
     */
    public void setFilename(String filename) {
    	try {
			this.filename = new String(filename.getBytes("ISO8859-1"),"UTF-8");
			downname = filename.split("---")[2];   
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    }
    public String getFilename() {
        try {
            return new String(filename.getBytes(),"ISO8859-1"); 
        } catch (UnsupportedEncodingException e) {
            return this.filename;
        }
    }
    public String getMimeType() {
        return mimeType;
    }
    public InputStream getInStream() {
    	String path=session.getServletContext().getRealPath("/");
    	String url = path+"doc/affix/"+tba.getIassistnoticeid()+"/"+filename; 
        try {
			inStream = new FileInputStream(url);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}     
        if (inStream == null) {
            inStream = new ByteArrayInputStream("Sorry,File not found !".getBytes());   
        }
        return inStream;  
    }
	public String getDownname() {
		return downname;
	}

	public void setDownname(String downname) {
		this.downname = downname;
	}


struts2配置文件
		<result name="filedown" type="stream">
				<param name="contentDisposition">attachment;filename="${downname}"</param> 
				<param name="contentType">${mimeType}</param>
				<param name="inputName">inStream</param>
		    </result>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics