ssh文件下载

struts2的文件下载是基于stream结果视图来进行的

struts代码


			
				
				inputStream
				
				attachment;filename=${name}
				
				application/octet-stream
				${filelength}
			
		


action代码

private InputStream inputStream;
	private String name;
	private int filelength;

	public String upload() throws IOException {
		ServletContext sc = ServletActionContext.getServletContext();
		String realPath = sc.getRealPath("/WEB-INF/upload/day04-js高级.txt");
		inputStream = new FileInputStream(realPath);
		filelength = inputStream.available();
		//设置文件名
		name = FilenameUtils.getName(realPath);//要进行URL编码,火狐浏览器除外
		//调用网上查找的FileUtils类防止乱码
                name = FileUtils.encodeDownloadFilename(name,ServletActionContext.getRequest().getHeader("user-agent")); 
		return SUCCESS;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public String getName() {
		return name;
	}

	public int getFilelength() {
		return filelength;
	}


//一个很好用的fileutils


 
  
private InputStream inputStream;
	private String name;
	private int filelength;

	public String upload() throws IOException {
		ServletContext sc = ServletActionContext.getServletContext();
		String realPath = sc.getRealPath("/WEB-INF/upload/day04-js高级.txt");
		inputStream = new FileInputStream(realPath);
		filelength = inputStream.available();
		//设置文件名
		name = FilenameUtils.getName(realPath);//要进行URL编码,火狐浏览器除外
		//调用网上查找的FileUtils类防止乱码
                name = FileUtils.encodeDownloadFilename(name,ServletActionContext.getRequest().getHeader("user-agent")); 
		return SUCCESS;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public String getName() {
		return name;
	}

	public int getFilelength() {
		return filelength;
	}


//一个很好用的fileutils



package it.he.service;

import java.io.IOException;
import java.net.URLEncoder;
import sun.misc.BASE64Encoder;
public class FileUtils {
        /**
         * 下载文件时,针对不同浏览器,进行附件名的编码
         *
         * @param filename
         *            下载文件名
         * @param agent
         *            客户端浏览器f
         * @return 编码后的下载附件名
         * @throws IOException
         */
        public static String encodeDownloadFilename(String filename, String agent)
                throws IOException {
            if (agent.contains("Firefox")) { // 火狐浏览器
                filename = "=?UTF-8?B?"
                        + new BASE64Encoder().encode(filename.getBytes("utf-8"))
                        + "?=";
                filename = filename.replaceAll("\r\n", "");
            } else { // IE及其他浏览器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+"," ");
            }
            return filename;
        }
}


你可能感兴趣的:(ssh文件下载)