这段时间公司在用SFTP服务,然后自己就整理了下sftp的工具,
流程如下
1、配置文件
##windows环境中的sftp
sftp.win.username=root
sftp.win.password=admin123
sftp.win.uploadPath=/
sftp.win.host=192.168.1.115
sftp.win.privateKey=dsjafkldsjfkajsdswe
sftp.win.port=22
img.win.basePath=http://localhost:8001/
##linux环境中的sftp
sftp.linux.username=
sftp.linux.password=
sftp.linux.uploadPath=
sftp.linux.host=5
sftp.linux.privateKey=
sftp.linux.port=
img.linux.basePath=
2、propertiesUtils工具类用于读取properties配置文件
package com.health.web.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration2.CombinedConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
/**
* 读取properties文件的工具类
* @author Lee
* @date 2018-10-30
**/
@Slf4j
public class PropertiesUtils {
private static CombinedConfiguration config = null;
public static boolean init(){
if (config != null)
return false;
try {
Configurations configs = new Configurations();
config = new CombinedConfiguration();
config.addConfiguration(configs.properties("common-sftp.properties"));
return true;
} catch (ConfigurationException e) {
log.error("PropertiesUtils:初始化配置文件错误", e);
return false;
}
};
public static void add(Configuration cfg){
config.addConfiguration(cfg);
};
public static boolean containsKey(String arg0) {
return config.containsKey(arg0);
}
public static BigDecimal getBigDecimal(String arg0, BigDecimal arg1) {
return config.getBigDecimal(arg0, arg1);
}
public static BigDecimal getBigDecimal(String arg0) {
return config.getBigDecimal(arg0);
}
public static BigInteger getBigInteger(String arg0, BigInteger arg1) {
return config.getBigInteger(arg0, arg1);
}
public static BigInteger getBigInteger(String arg0) {
return config.getBigInteger(arg0);
}
public static boolean getBoolean(String arg0, boolean arg1) {
return config.getBoolean(arg0, arg1);
}
public static Boolean getBoolean(String arg0, Boolean arg1) {
return config.getBoolean(arg0, arg1);
}
public static boolean getBoolean(String arg0) {
return config.getBoolean(arg0);
}
public static byte getByte(String arg0, byte arg1) {
return config.getByte(arg0, arg1);
}
public static Byte getByte(String arg0, Byte arg1) {
return config.getByte(arg0, arg1);
}
public static byte getByte(String arg0) {
return config.getByte(arg0);
}
public static double getDouble(String arg0, double arg1) {
return config.getDouble(arg0, arg1);
}
public static Double getDouble(String arg0, Double arg1) {
return config.getDouble(arg0, arg1);
}
public static double getDouble(String arg0) {
return config.getDouble(arg0);
}
public static float getFloat(String arg0, float arg1) {
return config.getFloat(arg0, arg1);
}
public static Float getFloat(String arg0, Float arg1) {
return config.getFloat(arg0, arg1);
}
public static float getFloat(String arg0) {
return config.getFloat(arg0);
}
public static int getInt(String arg0, int arg1) {
return config.getInt(arg0, arg1);
}
public static int getInt(String arg0) {
return config.getInt(arg0);
}
public static Integer getInteger(String arg0, Integer arg1) {
return config.getInteger(arg0, arg1);
}
public static Iterator<?> getKeys() {
return config.getKeys();
}
public static Iterator<?> getKeys(String arg0) {
return config.getKeys(arg0);
}
public static List<?> getList(String arg0, List<?> arg1) {
return config.getList(arg0, arg1);
}
public static List<?> getList(String arg0) {
return config.getList(arg0);
}
public static long getLong(String arg0, long arg1) {
return config.getLong(arg0, arg1);
}
public static Long getLong(String arg0, Long arg1) {
return config.getLong(arg0, arg1);
}
public static long getLong(String arg0) {
return config.getLong(arg0);
}
public static Properties getProperties(String arg0) {
return config.getProperties(arg0);
}
public static Object getProperty(String arg0) {
return config.getProperty(arg0);
}
public static short getShort(String arg0, short arg1) {
return config.getShort(arg0, arg1);
}
public static Short getShort(String arg0, Short arg1) {
return config.getShort(arg0, arg1);
}
public static short getShort(String arg0) {
return config.getShort(arg0);
}
public static String getString(String arg0, String arg1) {
return config.getString(arg0, arg1);
}
public static String getString(String arg0) {
return config.getString(arg0);
}
public static String[] getStringArray(String arg0) {
return config.getStringArray(arg0);
}
public static boolean isEmpty() {
return config.isEmpty();
}
}
3、SFTPUtils工具类
package com.health.web.common.utils;
import com.jcraft.jsch.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.util.Properties;
import java.util.UUID;
import java.util.Vector;
/**
* SFTP工具类
* @author Lee
* @date 2018-10-30
**/
@Slf4j
@Data
public class SFTPUtil {
private ChannelSftp sftp;
private Session session;
//SFTP用户名
private String username;
//SFTP用户密码
private String password;
//SFTP上传基础路径
private String uploadPath;
//SFTP私钥
private String privateKey;
//SFTP服务地址
private String host;
//SFTP端口
private int port;
//图片访问基本地址
private String basePath;
public SFTPUtil(){
super();
}
//构造基于密码认证的sftp对象--非配置文件加载
public SFTPUtil(String username, String password, String host, int port,String uploadPath) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
this.uploadPath = uploadPath;
}
//构造基于秘钥认证的sftp对象--非配置文件加载
public SFTPUtil(String username, String host, int port, String privateKey,String uploadPath) {
this.username = username;
this.host = host;
this.port = port;
this.privateKey = privateKey;
this.uploadPath = uploadPath;
}
//初始化数据
public void SFTPUtilInit(){
boolean res = PropertiesUtils.init();
Boolean ifWin = SFTPUtil.isWindows();
if(ifWin){
username = PropertiesUtils.getString("sftp.win.username");
password = PropertiesUtils.getString("sftp.win.password");
port = PropertiesUtils.getInt("sftp.win.port");
uploadPath = PropertiesUtils.getString("sftp.win.uploadPath");
host = PropertiesUtils.getString("sftp.win.host");
basePath = PropertiesUtils.getString("img.win.basePath");
}else{
username = PropertiesUtils.getString("sftp.linux.username");
password = PropertiesUtils.getString("sftp.linux.password");
port = PropertiesUtils.getInt("sftp.linux.port");
uploadPath = PropertiesUtils.getString("sftp.linux.uploadPath");
host = PropertiesUtils.getString("sftp.linux.host");
basePath = PropertiesUtils.getString("img.linux.basePath");
}
}
//判断是否是windows系统
public static Boolean isWindows(){
String op = System.getProperties().getProperty("os.name");
if (StringUtils.isNotBlank(op) && op.toLowerCase().startsWith("win")) {
return true;
} else {
return false;
}
}
//连接SFTP服务
public Boolean login(){
//初始化数据
SFTPUtilInit();
try {
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();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
e.printStackTrace();
return false;
}
return true;
}
//关闭Server服务
public void logout(){
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
if (session != null) {
if (session.isConnected()) {
session.disconnect();
}
}
}
/**
* 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory
* @param directory 上传到该目录
* @param sftpFileName sftp端文件名
* @param input 输入流
*/
public void upload(String directory, String sftpFileName, InputStream input) throws SftpException{
try {
sftp.cd(uploadPath);
sftp.cd(directory);
} catch (SftpException e) {
//目录不存在,则创建文件夹
String [] dirs=directory.split(File.separator);
String tempPath=uploadPath;
for(String dir:dirs){
if(null== dir || "".equals(dir)) continue;
tempPath+=File.separator+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 {
sftp.cd(uploadPath);
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 {
sftp.cd(uploadPath);
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
InputStream is = sftp.get(downloadFile);
byte[] fileData = IOUtils.toByteArray(is);
return fileData;
}
/**
* 删除文件
* @param directory 要删除文件所在目录
* @param deleteFile 要删除的文件
*/
public void delete(String directory, String deleteFile) throws SftpException{
sftp.cd(uploadPath);
sftp.cd(directory);
sftp.rm(deleteFile);
}
/**
* 列出目录下的文件
* @param directory 要列出的目录
*/
public Vector<?> listFiles(String directory) throws SftpException {
sftp.cd(uploadPath);
return sftp.ls(directory);
}
public static void main(String[] args) {
SFTPUtil util = new SFTPUtil();
Boolean loginRes = util.login();
if(loginRes){
File file = new File("G:/a.jpg");
InputStream is = null;
try {
is = new FileInputStream(file);
util.upload("/jialong/wenhao",UUID.randomUUID().toString()+".jpg",is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
util.logout();
}
}
}
}
4、图片批量上传
/**
* 保存-上传照片-批量
*/
@RequestMapping("/addBatch")
public R save( @RequestParam(value="file",required=false) MultipartFile[] file,HttpServletRequest request){
UmsMember userHolder = ThreadUtils.getUserHolder();
if(userHolder!=null && StringUtils.isNotBlank(userHolder.getUserCode())){
if (file!=null && file.length>0) {
SFTPUtil util = new SFTPUtil();
Boolean loginRes = util.login();
//数据库存储
List<UserCompImg> userCompImgList = new ArrayList<>();
UserCompImg userCompImg = null;
if(loginRes){
String returnUrl = File.separator+"userCompImg"+File.separator;//存储路径
InputStream is = null;
BufferedImage image = null;
try {
for (int i = 0; i < file.length; i++) {
String fileName=file[i].getOriginalFilename();//获取文件名加后缀
if(fileName!=null&&fileName!=""){
String path = request.getSession().getServletContext().getRealPath(returnUrl); //文件存储位置
String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+suffix;//新的文件名
}
is = file[i].getInputStream();
util.upload(returnUrl,fileName,is);
userCompImg = new UserCompImg();
userCompImg.setUserCompImgCode(UUID.randomUUID().toString());
userCompImg.setUserCode(userHolder.getUserCode());
userCompImg.setImgUrl(returnUrl+File.separator+fileName);
userCompImg.setCreateTime(new Date());
userCompImg.setUpdateTime(new Date());
userCompImgList.add(userCompImg);
}
} catch (IOException e) {
log.error("====>file转inputStream失败");
e.printStackTrace();
} catch (SftpException e) {
log.error("====>sftp上传失败");
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
util.logout();
}
}else{
log.error("====>sftp连接失败");
return R.error(PublicResultConstant.FAILED.result, PublicResultConstant.FAILED.getMsg());
}
//批量插入数据库
Integer res = userCompImgService.addBatchUserCompImg(userCompImgList);
if(res>0){
return R.ok();
}else{
return R.error(PublicResultConstant.FAILED.result, PublicResultConstant.FAILED.getMsg());
}
}
}
return R.error(PublicResultConstant.PARAM_ERROR.result, PublicResultConstant.PARAM_ERROR.getMsg());
}
5、Nginx配置
server {
listen 8001;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root E:/FileServer/;
index index.html index.htm;
add_header 'Access-Control-Allow-Origin' *;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}