91名师指路-头部
91名师指路

java 使用sftp 实现文件上传和下载

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

1 引入jar包

<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

2 工具类。

package com.mszl.utils;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.util.Vector;

import javax.imageio.ImageIO;

import org.apache.logging.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.manulife.vo.SftpVO;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SftpUtils {

private static final Logger LOG = org.apache.logging.log4j.LogManager.getLogger(SftpUtils.class);
private static final String host = SftpVO.ip;
private static final int port = SftpVO.port;
private static final String username = SftpVO.account;
private static final String password = SftpVO.password;
public static final String directory = SftpVO.directory;

private static ChannelSftp sftp;

// private static SftpUtils instance = null;

private SftpUtils() {

}

public static SftpUtils getInstance() {
// if (instance == null) {
SftpUtils instance = new SftpUtils();
sftp = instance.connect(host, port, username, password); // 获取连接
// }
return instance;
}

/**
* 连接sftp服务器
* @param host 主机
* @param port 端口
* @param username 用户名
* @param password 密码
* @return
*/
public ChannelSftp connect(String host, int port, String username, String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
LOG.info("SFTP Session connected.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
LOG.info("Connected to " + host);
} catch (Exception e) {
LOG.error(e.getMessage());
}
return sftp;
}

/**
* 上传文件
* @param directory 上传的目录
* @param uploadFile 要上传的文件
*/
public boolean upload(String directory, String uploadFile) {
try {
sftp.cd(directory);
File file = new File(uploadFile);
FileInputStream fileInputStream = new FileInputStream(file);
sftp.put(fileInputStream, file.getName());
fileInputStream.close();
return true;
} catch (Exception e) {
LOG.error(e.getMessage());
return false;
}
}

// 读取网络图片并将图片上传到服务器
public boolean uploadNetwork(String directory, String url, String imageName) {
boolean flag=false;
try {
sftp.cd(directory);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
sftp.put(inputStream, imageName);
inputStream.close();
flag=true;
}
} catch (Exception e) {
LOG.error(e.getMessage());
}
return flag;
}


// 读取网络图片并将图片上传到服务器(改变图片大小上传)
public boolean uploadNetworkChangeImageSize(String directory, String url, String imageName,int width, int height ) {
boolean flag=false;
try {
sftp.cd(directory);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
Image srcImg = null;
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
srcImg = ImageIO.read(inputStream);
BufferedImage buffImg = null;
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
buffImg.getGraphics().drawImage(
srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0,
0, null);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(buffImg, "JPEG", os);
InputStream input = new ByteArrayInputStream(os.toByteArray());

sftp.put(input, imageName);
inputStream.close();
input.close();
flag=true;
}
} catch (Exception e) {
LOG.error(e.getMessage());
}
return flag;
}

// 读取网络图片
public static InputStream getImageStream(String url) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
return inputStream;
}
} catch (IOException e) {
log.warn(e.getMessage(), e);
}
return null;
}

/**
* 下载文件
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 存在本地的路径
*/
public File download(String directory, String downloadFile, String saveFile) {
try {
sftp.cd(directory);
File file = new File(saveFile);
FileOutputStream fileOutputStream = new FileOutputStream(file);
sftp.get(downloadFile, fileOutputStream);
fileOutputStream.close();
return file;
} catch (Exception e) {
LOG.error(e.getMessage());
return null;
}
}

/**
* 下载文件
* @param downloadFilePath 下载的文件完整目录
* @param saveFile 存在本地的路径
*/
public File download(String downloadFilePath, String saveFile) {
try {
int i = downloadFilePath.lastIndexOf('/');
if (i == -1)
return null;
sftp.cd(downloadFilePath.substring(0, i));
File file = new File(saveFile);
FileOutputStream fileOutputStream = new FileOutputStream(file);
sftp.get(downloadFilePath.substring(i + 1), fileOutputStream);
fileOutputStream.close();
return file;
} catch (Exception e) {
LOG.error(e.getMessage());
return null;
}
}

/**
* 删除文件
* @param directory 要删除文件所在目录
* @param deleteFile 要删除的文件
*/
public void delete(String directory, String deleteFile) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
LOG.error(e.getMessage());
}
}

public void disconnect() {
try {
sftp.getSession().disconnect();
} catch (JSchException e) {
LOG.error(e.getMessage());
}
sftp.quit();
sftp.disconnect();
}

/**
* 列出目录下的文件
* @param directory 要列出的目录
* @throws SftpException
*/
public Vector<LsEntry> listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}

public static void main(String[] args) throws IOException {
SftpUtils sf = SftpUtils.getInstance();
sf.uploadNetworkChangeImageSize(directory, "http://www.91mszl.com/images/logo.png",
"aaa.jpg", 210,370);
//sf.uploadNetwork(directory, "http://www.91mszl.com/images/logo.png", "abc.jpg");

// sf.upload(directory, "http://www.91mszl.com/images/logo.png"); // 上传文件
// sf.download(directory, "2.png", "C:\\Users\\hp\\Desktop\\1212.png");
// File download = sf.download("F:\\images\\2.jpg", "/users/cpuat/weidong/2.jpg");
// sf.delete(directory, deleteFile); // 删除文件
Vector<LsEntry> files = null; // 查看文件列表
try {
files = sf.listFiles(directory);
} catch (SftpException e) {
log.warn(e.getMessage(), e);
}
for (LsEntry file : files) {
}
sf.disconnect();
}





}


2019-08-23 14:13:58     阅读(1638)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部