您的位置:首页 > 编程语言 > PHP开发

Utils 图片通过Url获取流用Sftp向文件服务器存储

2017-11-29 16:57 363 查看
实现功能:通过图片Url获取流用Sftp向文件服务器存储图片

/**
* 上传图片到指定的服务器,返回上传到文件服务器图片名称
* @param pictureUrl 需要上传的图片Url地址,例https://www.baidu.com/img/bd_logo1.png
* @return String    上传图片的名称
*/
public String sftpUpload(String pictureUrl) {}

/**
* 上传图片到指定的服务器,返回上传到文件服务器图片名称
* @param pictureUrl 需要上传的图片Url地址,例https://www.baidu.com/img/bd_logo1.png
* @param upleadPath 指定上传路径
* @return String    上传图片的名称
*/
public String sftpUpload(String pictureUrl, String upleadPath) {}

SFTP jar包: https://pan.baidu.com/s/1gfw8EYn 密码:knpz

<!-- sftp依赖包 -->  

<dependency>  

      <groupId>com.jcraft</groupId>  

      <artifactId>jsch</artifactId>  

      <version>0.1.53</version>  

</dependency>

HttpsURLConnection_SftpFile_Upload 代码如下:

import java.io.ByteArrayInputStream;
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.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
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;
import com.neusoft.util.PropertiesUtil;
public class HttpsURLConnection_SftpFile_Upload {

private static final  Logger log = LoggerFactory.getLogger(HttpsURLConnection_SftpFile_Upload.class);
private ChannelSftp sftp;
private Session session;
/** FTP 登录用户名*/
private static String username = PropertiesUtil.getPropertie("SFTP_VS_USERNAME");
/** FTP 登录密码*/
private static String password = PropertiesUtil.getPropertie("SFTP_VS_PASSWORD");
/** 私钥 */
private String privateKey;
/** FTP 服务器地址IP地址*/
private static String host = PropertiesUtil.getPropertie("SFTP_VS_HOST");
/** FTP 端口*/
private int port = Integer.valueOf(PropertiesUtil.getPropertie("SFTP_VS_PORT")).intValue();

/**
* 构造基于密码认证的sftp对象
* @param userName
* @param password
* @param host
* @param port
*/
public HttpsURLConnection_SftpFile_Upload(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}

/**
* 构造基于秘钥认证的sftp对象
* @param userName
* @param host
* @param port
* @param privateKey
*/
public HttpsURLConnection_SftpFile_Upload(String username, String host, int port, String privateKey) {
this.username = username;
this.host = host;
this.port = port;
this.privateKey = privateKey;
}

public HttpsURLConnection_SftpFile_Upload(){}

/**
* 连接sftp服务器
*
* @throws Exception
*/
public void login(){
try {
JSch jsch = new JSch();
if (privateKey != null) {
jsch.addIdentity(privateKey);// 设置私钥
log.info("sftp connect,path of private key file:{}" , privateKey);
}
log.info("sftp connect by host:{} username:{}",host,username);

session = jsch.getSession(username, host, port);
log.info("Session is build");
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");

session.setConfig(config);
session.connect();
log.info("Session is connected");

Channel channel = session.openChannel("sftp");
channel.connect();
log.info("channel is connected");

sftp = (ChannelSftp) channel;
log.info(String.format("sftp server host:[%s] port:[%s] is connect successfull", host, port));
} catch (JSchException e) {
log.error("Cannot connect to specified sftp server : {}:{} \n Exception message is: {}", new Object[]{host, port, e.getMessage()});
}
}

public static void main(String[] args) throws SftpException, IOException {
HttpsURLConnection_SftpFile_Upload sftp = new HttpsURLConnection_SftpFile_Upload("用户名", "密码", "地址", 22);
sftp.login();
File file = new File("C:\\new.jpg");
InputStream is = new FileInputStream(file);
sftp.upload("/upload", "ceshi.jpg", is);
sftp.logout();
}

/**
* 上传图片到指定的服务器,返回上传到文件服务器图片名称
* @param pictureUrl 需要上传的图片地址
* @return String    上传文件的地址
*/
public String sftpUpload(String pictureUrl) {
InputStream inputStream = null;
try{
if ((pictureUrl == null) || ("".equals(pictureUrl)) || ("null".equals(pictureUrl))) {
return "";
}
try{
URL url = new URL(pictureUrl);

HttpsURLConnection conn =  (HttpsURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
SSLContext sslContext = createIgnoreVerifySSL();//*航空管家更新https协议后新增*
javax.net.ssl.SSLSocketFactory ssf = sslContext.getSocketFactory();//*航空管家更新https协议后新增*
conn.setSSLSocketFactory(ssf);//*航空管家更新https协议后新增*
conn.connect();

inputStream = conn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
log.info(pictureUrl + "获取图片流报错了==e.getMessage()"+e.getMessage()+"==e.getCause()"+e.getCause());

logout();
if (inputStream != null)
try {
inputStream.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
return "";
}

HttpsURLConnection_SftpFile_Upload sftp = new HttpsURLConnection_SftpFile_Upload(username, password, host, this.port);
sftp.login();

Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
if (pictureUrl.contains("/")) {
String[] split = pictureUrl.split("/");
pictureUrl = split[(split.length - 1)];
}
String fileName = df.format(date) + pictureUrl;

sftp.upload("/upload", fileName, inputStream);
sftp.logout();
inputStream.close();
String str1 = fileName;
return str1;
} catch (Exception e) {
e.printStackTrace();
log.info(pictureUrl + "上传到对面服务器失败!");
} finally {
logout();
if (inputStream != null) {
try {
inputStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
/**
* 上传图片到指定的服务器,返回上传到文件服务器图片名称
* @param pictureUrl 需要上传的图片地址
* @param upleadPath 指定上传路径
* @return String    上传文件的地址
*/
public String sftpUpload(String pictureUrl, String upleadPath) {
InputStream inputStream = null;
try{
if ((pictureUrl == null) || ("".equals(pictureUrl)) || ("null".equals(pictureUrl))) {
return "";
}
try{
URL url = new URL(pictureUrl);

HttpsURLConnection conn =  (HttpsURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
SSLContext sslContext = createIgnoreVerifySSL();//*航空管家更新https协议后新增*
javax.net.ssl.SSLSocketFactory ssf = sslContext.getSocketFactory();//*航空管家更新https协议后新增*
conn.setSSLSocketFactory(ssf);//*航空管家更新https协议后新增*
conn.connect();

inputStream = conn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
log.info(pictureUrl + "获取图片流报错了==e.getMessage()"+e.getMessage()+"==e.getCause()"+e.getCause());

logout();
if (inputStream != null)
try {
inputStream.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return "";
}

HttpsURLConnection_SftpFile_Upload sftp = new HttpsURLConnection_SftpFile_Upload(username, password, host, this.port);
sftp.login();

Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
if (pictureUrl.contains("/")) {
String[] split = pictureUrl.split("/");
pictureUrl = split[(split.length - 1)];
}
String fileName = df.format(date) + pictureUrl;

sftp.upload(upleadPath, fileName, inputStream);
sftp.logout();
inputStream.close();
String str1 = fileName;
return str1;
} catch (Exception e) {
e.printStackTrace();
log.info(pictureUrl + "上传到对面服务器失败!" + e.getMessage());
} finally {
logout();
if (inputStream != null) {
try {
inputStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}

/**
* 关闭连接 server
*/
public void logout(){

if (sftp != null) {
if (sftp.isConnected()) {
try{
sftp.quit();
sftp.disconnect();
}catch(Exception e){
e.printStackTrace();
}
log.info("sftp is closed already");
}
}
if (session != null) {
if (session.isConnected()) {
try{
session.disconnect();
}catch(Exception e){
e.printStackTrace();
}
log.info("sshSession is closed already");
}
}
}

/**
* 将输入流的数据上传到sftp作为文件
*
* @param directory
*            上传到该目录
* @param sftpFileName
*            sftp端文件名
* @param in
*            输入流
* @throws SftpException
* @throws Exception
*/
public void upload(String directory, String sftpFileName, InputStream input) throws SftpException{
try {
sftp.cd(directory);
} catch (SftpException e) {
log.warn("directory is not exist");
sftp.mkdir(directory);
sftp.cd(directory);
}
sftp.put(input, sftpFileName);
log.info("file:{} is upload successful" , sftpFileName);

}

/**
*
*    绕过证书验证
*/
public static SSLContext createIgnoreVerifySSL() {

SSLContext sc=null;
try {
sc = SSLContext.getInstance("SSL");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}

@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}

@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};

sc.init(null, new TrustManager[] { trustManager },null);
}catch (NoSuchAlgorithmException e) {
log.info("FlightScheduledUtil/createIgnoreVerifySSL/NoSuchAlgorithmException" + e);
} catch (KeyManagementException e) {
log.info("FlightScheduledUtil/createIgnoreVerifySSL/KeyManagementException" + e);
}
return sc;
}
}


希望对你有帮助,祝你有一个好心情,加油!

若有错误、不全、可优化的点,欢迎纠正与补充!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Utils Sftp