視頻文件sftp服務下載之SFTPUtil

sftp服務器

即安全 FTP 服務器,幫助用戶通過安全文件傳輸協議,如 SSH 文件傳輸協議 FTP 或使用 SSL/TLS 傳輸文件。該傳輸可以通過服務器到服務器或客戶端 – 服務器配置來實現。安全的 FTP 服務器可幫助企業通過互聯網或不安全的網絡安全地發送機密文件。

SFTPUtil 實現代碼

package glodon.govp.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
/** 
* 類說明 sftp工具類
*/
public class SFTPUtil {
    private transient Logger log = LoggerFactory.getLogger(this.getClass());  
    
    private ChannelSftp sftp;  
        
    private Session session;  
    /** SFTP 登錄用戶名*/    
    private String username; 
    /** SFTP 登錄密碼*/    
    private String password;  
    /** 私鑰 */    
    private String privateKey;  
    /** SFTP 服務器地址IP地址*/    
    private String host;  
    /** SFTP 端口*/  
    private int port;  
        
    
    /**  
     * 構造基於密碼認證的sftp對象  
     */    
    public SFTPUtil(String username, String password, String host, int port) {  
        this.username = username;  
        this.password = password;  
        this.host = host;  
        this.port = port;  
    } 
    
    /**  
     * 構造基於祕鑰認證的sftp對象 
     */  
    public SFTPUtil(String username, String host, int port, String privateKey) {  
        this.username = username;  
        this.host = host;  
        this.port = port;  
        this.privateKey = privateKey;  
    }  
    
    public SFTPUtil(){}  
    
    
    /** 
     * 連接sftp服務器 
     */  
    public void login(){  
        try {  
        	com.jcraft.jsch.Logger logger = new SettleLogger();
            JSch.setLogger(logger);
            JSch jsch = new JSch();  
            if (privateKey != null) {  
                jsch.addIdentity(privateKey);// 設置私鑰  
            }  
    
            session = jsch.getSession(username, host, port);  
           
            if (password != null) {  
                session.setPassword(password);    
            }  
            Properties config = new Properties();  
            config.put("StrictHostKeyChecking", "no");  
                
            session.setConfig(config);  
            session.connect(2500);  
              
            Channel channel = session.openChannel("sftp");  
            channel.connect();  
    
            sftp = (ChannelSftp) channel;  
        } catch (JSchException e) {  
            e.printStackTrace();
        }  
    }    
    
    /** 
     * 關閉連接 server  
     */  
    public void logout(){  
        if (sftp != null) {  
            if (sftp.isConnected()) {  
                sftp.disconnect();  
            }  
        }  
        if (session != null) {  
            if (session.isConnected()) {  
                session.disconnect();  
            }  
        }  
    }  
 
    
    /**  
     * 將輸入流的數據上傳到sftp作爲文件。文件完整路徑=basePath+directory
     * @param basePath  服務器的基礎路徑 
     * @param directory  上傳到該目錄  
     * @param sftpFileName  sftp端文件名  
     * @param in   輸入流  
     */  
    public void upload(String basePath,String directory, String sftpFileName, InputStream input) throws SftpException{  
        try {   
            sftp.cd(basePath);
            sftp.cd(directory);  
        } catch (SftpException e) { 
            //目錄不存在,則創建文件夾
            String [] dirs=directory.split("/");
            String tempPath=basePath;
            for(String dir:dirs){
            	if(null== dir || "".equals(dir)) continue;
            	tempPath+="/"+dir;
            	try{ 
            		sftp.cd(tempPath);
            	}catch(SftpException ex){
            		sftp.mkdir(tempPath);
            		sftp.cd(tempPath);
            	}
            }
        }  
        sftp.put(input, sftpFileName);  //上傳文件
    } 
    
 
    /** 
     * 下載文件。
     * @param directory 下載目錄  
     * @param downloadFile 下載的文件 
     * @param saveFile 存在本地的路徑 
     */    
    public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{  
        if (directory != null && !"".equals(directory)) {  
            sftp.cd(directory);  
        }  
        File file = new File(saveFile);  
        sftp.get(downloadFile, new FileOutputStream(file));  
    }  
    
    /**  
     * 下載文件 
     * @param directory 下載目錄 
     * @param downloadFile 下載的文件名 
     * @return 字節數組 
     */  
    public byte[] download(String directory, String downloadFile) throws SftpException, IOException{  
        if (directory != null && !"".equals(directory)) {  
            sftp.cd(directory);  
        }  
        InputStream is = sftp.get(downloadFile);  
          
        byte[] fileData = IOUtils.toByteArray(is);  
          
        return fileData;  
    }  
    /**  
     * 下載文件 
     * @param directory 下載目錄 
     * @param downloadFile 下載的文件名 
     * @return 字節流
     */  
    public InputStream downloadToInputStream(String directory, String downloadFile) throws SftpException, IOException{  
    	if (directory != null && !"".equals(directory)) {  
    		sftp.cd(directory);  
    	}  
    	InputStream is = sftp.get(downloadFile);  
    	
    	//byte[] fileData = IOUtils.toByteArray(is);  
    	
    	return is;  
    }  
    
    
    /** 
     * 刪除文件 
     * @param directory 要刪除文件所在目錄 
     * @param deleteFile 要刪除的文件 
     */  
    public void delete(String directory, String deleteFile) throws SftpException{  
        sftp.cd(directory);  
        sftp.rm(deleteFile);  
    }  
    
    
    /** 
     * 列出目錄下的文件 
     * @param directory 要列出的目錄 
     * @param sftp 
     */  
    public Vector<?> listFiles(String directory) throws SftpException {  
        return sftp.ls(directory);  
    }  
      
    //上傳文件測試
    public static void main(String[] args) throws SftpException, IOException {  
        SFTPUtil sftp = new SFTPUtil("用戶名", "密碼", "ip地址", 22);  
        sftp.login();  
        File file = new File("D:\\圖片\\t0124dd095ceb042322.jpg");  
        InputStream is = new FileInputStream(file);  
          
        sftp.upload("基礎路徑","文件路徑", "test_sftp.jpg", is);  
        sftp.logout();  
    }  
}

SFTPUtil的使用場景

主要是應用在,用戶從文件服務器上下載文件視頻(加密的)

SFTPUtil使用步驟

第一步構建SFTPUtil對象

SFTPUtil sftp = new SFTPUtil(video.getFileServerUserName(), video.getFileServerUserPass(), 
				video.getFileServerIp(), Integer.valueOf(video.getFileServerPort()));

第二步登錄sftp服務器
sftp.login();
第三步,向sftp服務器獲取數據流

 InputStream inputStream = sftp.downloadToInputStream(video.getDownUrl(), video.getDownUrl()+video.getFilename());

第四步,瀏覽器下載文件

 if(inputStream != null){
        	response.reset();
            response.setContentType("application/x-download;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=\"" +URLEncoder.encode(video.getFilename(),"UTF-8") + "\"");
            response.setCharacterEncoding("UTF-8");
            //創建緩衝區
            byte[] b= new byte[2048];  
            int len = 0; 
           OutputStream stream = response.getOutputStream();
           //循環將輸入流中的內容讀取到緩衝區當中  
           while((len = inputStream.read(b)) != -1){
           //輸出緩衝區的內容到瀏覽器,實現文件下載
                stream.write(b, 0, len);
            }
            //退出sftp服務器
           sftp.logout();
            stream.flush();
            stream.close();
            inputStream.close();
            inputStream =null;
}

maven依賴jar

<dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi</artifactId>
		    <version>3.9</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi-ooxml</artifactId>
		    <version>3.9</version>
		</dependency>
		<dependency>
		    <groupId>com.jcraft</groupId>
		    <artifactId>jsch</artifactId>
		    <version>0.1.54</version>
		</dependency>
		<dependency>
	       <groupId>net.lingala.zip4j</groupId>
	       <artifactId>zip4j</artifactId>
	       <version>1.3.2</version>
		</dependency> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章