java使用Sftp上传图片文件到Linux服务器上
需要依赖
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<!-- 为了使用@Slf4j注解 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
编写工具类,直接上代码,里面有注释直接就可以用;
@Slf4j
public class uploadUtil {
private static Session session;
private static ChannelSftp channelSftp;
public static ChannelSftp getSFTPClient(String ftpaddress, String ftpPassword,
String ftpUserName,int ftpPort) {
long startTime = System.currentTimeMillis();
JSch jsch = new JSch();
Channel channel = null;
try {
session = jsch.getSession(ftpUserName, ftpaddress,ftpPort);
session.setPassword(ftpPassword);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
long endTime = System.currentTimeMillis();
log.info("连接sftp成功耗时" + (endTime - startTime) + "毫秒");
return (ChannelSftp) channel;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static boolean isDirExist(String directory, ChannelSftp sftp) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = sftp.lstat(directory);
log.info("目录"+directory+"已存在");
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
log.info("目录"+directory+"不存在");
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
public static void createDir(String createpath, ChannelSftp sftp) {
try {
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString(),sftp)) {
sftp.cd(filePath.toString());
} else {
sftp.mkdir(filePath.toString());
log.info("创建目录"+filePath.toString()+"成功");
sftp.cd(filePath.toString());
log.info("进入目录"+filePath.toString());
}
}
sftp.cd(createpath);
} catch (SftpException e) {
}
}
public static void close() {
if (channelSftp != null && channelSftp.isConnected()) {
channelSftp.disconnect();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
log.info("关闭连接资源");
}
public static boolean uploadFile(String host, int port, String userName, String password, String remoteFile, InputStream in, String pathName){
try{
if (channelSftp == null || !channelSftp.isConnected()) {
channelSftp=getSFTPClient(host,password,userName,port);
}
if (isDirExist(remoteFile,channelSftp)) {
channelSftp.put(in, remoteFile + "/" +pathName);
log.info("文件上传成功,文件路径"+remoteFile + "/" +pathName);
close();
return true;
} else {
createDir(remoteFile ,channelSftp);
channelSftp.put(in, remoteFile + "/" +pathName);
log.info("文件上传成功,文件路径"+remoteFile + "/" +pathName);
close();
return true;
}
}catch(Exception e){
e.printStackTrace();
close();
}
return false;
}
public static boolean uploadDstFile(String host, int port, String userName, String password,
MultipartFile[] file, String remoteFile){
boolean b = false;
channelSftp = getConn(userName,password,host,port);
if (isConnected()) {
b = uploadFiles(file,remoteFile);
close();
}
return b;
}
private static boolean uploadFiles(MultipartFile[] file, String remoteFile) {
try {
for (int i = 0; i < file.length; i++) {
InputStream in=null;
in = file[i].getInputStream();
if(i==0){
remoteFile=remoteFile+"/"+file[i].getOriginalFilename().substring(0,file[i].getOriginalFilename().lastIndexOf("/"));
}
String originalFilename = file[i].getOriginalFilename().substring(file[i].getOriginalFilename().lastIndexOf("/"));
if (isDirExist(remoteFile, channelSftp)) {
channelSftp.put(in, remoteFile+"/"+originalFilename);
log.info("文件上传成功,文件路径" + remoteFile+"/"+originalFilename);
} else {
createDir(remoteFile, channelSftp);
channelSftp.put(in, remoteFile+"/"+originalFilename);
log.info("文件上传成功,文件路径"+ remoteFile+"/"+originalFilename);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
close();
return true;
}
}
下面来测试一下
前端写一个简单的文件和视频上传
<form action="/loign1" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
var formData = new FormData($("#uploadForm")[0])
formData.append('fileimages', $('#file')[0].files[0])
$.ajax({
type: "post",
url: "地址",
async: false,
cache: false,
contentType: false,
processData: false,
data: formData,
dataType: "json",
success: function(result){
}
});
后台测试
@RequestMapping(value = "/loign1",method = RequestMethod.POST)
public String hellofile(HttpServletRequest request,MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
boolean root = uploadUtil.uploadFile();
return "";
}
spring:
servlet:
multipart:
max-file-size: 9967920994
max-request-size: 9967920994
上传文件夹测试
<form action="/loign3" method="post" enctype="multipart/form-data">
<input type="file" name="file" webkitdirectory>
<input type="submit">
</form>
后台测试
@RequestMapping(value = "/loign3",method = RequestMethod.POST)
public String hello3(HttpServletRequest request,MultipartFile[] file) throws IOException {
if (file!=null) {
boolean root = uploadUtil.uploadDstFile();
}
return "";
}