项目中遇到从远程Linux服务器上获取文件,在浏览器页面实现下载功能。Linux服务器安装Tomcat

一开始是后端直接拼接文件url路径返回前端,这种方式对于普通文件(.xlsx .docx .txt)等可以实现,但是对于一些配置类文件(如: .swp .xml )则不行,会在页面直接打开。

最后还是用下面的两种方式去实现。

方式一:利用文件的url地址建立URL连接,获取文件流,输出到浏览器;
但是这种方式无法进行用户名、密码校验,如果远程服务器需要用户登录则无法实现,可以参考第二中种方法。

String urlPath ="http://10.54.22.xx:8088/download/resultdir/bufferdir/2021-09-28/bufferDir/xxx.csv";
File file = null;
try{
    URL url = new URL(urlPath);
    //建立连接
    URLConnection conn = url.openConnection();
    //http的连接类
    HttpURLConnection httpConn = (HttpURLConnection) conn;
    //设置超时时间
    httpConn.setConnectTimeout(1000*5);
    //设置请求方式,默认是G2T
    httpConn.setRequestMethod("POST");
    // 设置字符编码
    httpConn.setRequestProperty("Charset", "UTF-8");
    httpConn.connect();
    //获取文件大小
    int fileLength = httpConn.getContentLength();
    logger.info("下载的文件大小:"+fileLength/(1024*1024)+"MB");
    //从请求中获取资源
    BufferedInputStream inputStream = new BufferedInputStream(httpConn.getInputStream());
    //文件输出到本地路径下
    OutputStream out = new FileOutputStream(new File("D:/download"));
    		//如果要输出到浏览器,则需要设置response的头信息
    		response.addHeader("Access-Contro1-A11ow-0rigin”, "*");
    		response.setCharacterEncoding("GBK");
    		OutputStream out = response.getOutputStream();
    int size;
    int len = 0;
    byte[] bytes = new byte[2048];
    while ((size = inputStream.read(bytes)) != -1){
        len += size;
        out.write(bytes,0,size);
        //打印下载进度
        logger.info("下载了:"+len*100/fileLength + "%\n");
    }
    inputStream.close();
    out.close();
    logger.info("文件下载成功!");

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

方式二:通过SCPClient建立连接,获取文件流,输出到浏览器。

因为我这边文件服务器是基于ssh传输文件的SCP协议,故需要创建SCPClient,如果是基于TCP传输,则需要创建FTPClient

1 创建连接
public Connection getConn(String ip, int port, String username, String password){
	//创建远程连接,默认连接端口为22,如果不使用默认,可以使用方法
	//new Connection(ip, port)创建对象
	conn = new Connection(ip, port);        
	try {
		//连接远程服务器
		conn.connect();
		//使用用户名和密码登录
        return conn.authenticateWithPassword(username, password);
	} catch (IOException e) {   
		e.printStackTrace();
  }
  return conn;
}
2 创建SCPClient对象,调用get()方法输出文件流。
	/**
	 * 流式输出,用于浏览器下载
	 * @param conn
	 * @param filePath
	 * @param outputStream
	 */
	public void downloadFile(Connection conn, String filePath,ServletOutputStream outputStream){
		SCPClient sc = new SCPClient(conn);
		try {
			sc.get(filePath, outputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐