java 判断操作系统类型,通过ChannelSftp上传文件到服务器目录

    @Autowired
    FtpUtil ftpUtil;

String imgBase64Str = acsPassedInfo.getFaceStr();
InputStream inputStream = convertStringToInputStream(imgBase64Str);
String os = System.getProperty("os.name");//判断操作系统
            if (os.toLowerCase().startsWith("win")) {
                try {
                    ftpUtil.getConnect("101.220.303.404", "22", "root", "123456789");
                    ftpUtil.uploadFile("", filePath, fileName, inputStream);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                imageBase64Converter.convertBase64ToFile(imgBase64Str, filePath, fileName, inputStream);
            }

FTP

package com.rj.patrol.server.console.utils.ImgUtil;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Properties;

@Service
public class FtpUtil {
	private static final Logger loggerMonitor = LoggerFactory.getLogger("monitor");

	/**
	 * FTPClient对象
	 **/
	private static ChannelSftp ftpClient = null;
	/**
	 *
	 */
	private static Session sshSession = null;

	/**
	 * 连接服务器
	 * @param host
	 * @param port
	 * @param userName
	 * @param password
	 * @return
	 * @throws Exception
	 */
	public static ChannelSftp getConnect(String host, String port, String userName, String password)
			throws Exception {
		try {
			JSch jsch = new JSch();
			// 获取sshSession
			sshSession = jsch.getSession(userName, host, Integer.parseInt(port));
			// 添加s密码
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			// 开启sshSession链接
			sshSession.connect();
			// 获取sftp通道
			ftpClient = (ChannelSftp) sshSession.openChannel("sftp");
			// 开启
			ftpClient.connect();
			loggerMonitor.debug("success ..........");
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("连接sftp服务器异常。。。。。。。。");
		}
		return ftpClient;
	}

	/**
	 * 下载文件
	 * @param ftp_path	服务器文件路径
	 * @param save_path	下载保存路径
	 * @param oldFileName	服务器上文件名
	 * @param newFileName	保存后新文件名
	 * @throws Exception
	 */
	public static void download(String ftp_path, String save_path, String oldFileName, String newFileName)
			throws Exception {
		FileOutputStream fos = null;
		try {
			ftpClient.cd(ftp_path);
			File file = new File(save_path);
			if (!file.exists()) {
				file.mkdirs();
			}
			String saveFile = save_path + newFileName;
			File file1 = new File(saveFile);
			fos = new FileOutputStream(file1);
			ftpClient.get(oldFileName, fos);
		} catch (Exception e) {
			loggerMonitor.error("下载文件异常............", e.getMessage());
			throw new Exception("download file error............");
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
					e.printStackTrace();
					throw new Exception("close stream error..........");
				}
			}
		}
	}

	/**
	 * 上传
	 * @param upload_path 上传文件路径	
	 * @param ftp_path	服务器保存路径	
	 * @param newFileName	新文件名
	 * @throws Exception
	 */
	public static void uploadFile(String upload_path, String ftp_path, String newFileName, InputStream input) throws Exception {
		FileInputStream fis = null;
		try {
//			fis = new FileInputStream(new File(upload_path));
			ftpClient.cd(ftp_path);
			ftpClient.put(input, newFileName);
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("Upload file error.");
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new Exception("close stream error.");
				}
			}
		}
	}

	/**
	 * 关闭
	 *
	 * @throws Exception
	 */
	public static void close() throws Exception {
		loggerMonitor.debug("close............");
		try {
			ftpClient.disconnect();
			sshSession.disconnect();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new Exception("close stream error.");
		}
	}

	public static void main(String[] args) {
		try {
			getConnect("ip地址", "22", "用户名", "密码");
			close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

本地

  /**
     * 将base64字符串,生成文件
     */
    public File convertBase64ToFile(String fileBase64String, String filePath, String fileName, InputStream input) {

        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
//            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
//                dir.mkdirs();
//            }
            //判断文件父目录是否存在
            if (!dir.getParentFile().exists()) {
                dir.getParentFile().mkdir();
            }

//            BASE64Decoder decoder = new BASE64Decoder();
//            byte[] bfile = decoder.decodeBuffer(fileBase64String);
//
//            file = new File(filePath + File.separator + fileName);
//            fos = new FileOutputStream(file);
//            bos = new BufferedOutputStream(fos);
//            bos.write(bfile);

            //手动写的
            OutputStream out = new FileOutputStream(new File(filePath, fileName));
            InputStream in = input;
            int length = 0;
            byte[] buf = new byte[1024];
            // in.read(buf) 每次读到的数据存放在 buf 数组中
            while ((length = in.read(buf)) != -1) {
                //在 buf 数组中 取出数据 写到 (输出流)磁盘上
                out.write(buf, 0, length);
            }
            in.close();
            out.close();

            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值