FTP上传、下载实现,FTP级联创建目录实现

This commit is contained in:
2018-05-08 22:50:25 +08:00
parent d2122c2896
commit 495b1e4202
10 changed files with 288 additions and 86 deletions

17
pom.xml
View File

@@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RC2</version>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
@@ -54,9 +54,14 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>1.5.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
@@ -86,6 +91,14 @@
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
</dependencies>

View File

@@ -62,12 +62,10 @@ public class DeleteController {
return false;
} else {
if (filepath.isFile()){
deleteFile(resfile.getColfilepath(),resfile.getColfileid());
return true;
return deleteFile(resfile.getColfilepath(),resfile.getColfileid());
}
else{
deleteDirectory(resfile.getColfilepath());
return true;
return deleteDirectory(resfile.getColfilepath());
}

View File

@@ -157,7 +157,6 @@ public class DownLoadController {
TbFile file = new TbFile();
file.setColfileid(fileId);
TbFile tbFile = fileService.findFileById(file);
System.out.println("【file】"+tbFile.toString());
String ctxPath = tbFile.getColfilepath();
@@ -170,13 +169,13 @@ public class DownLoadController {
response.setHeader("Content-disposition", "attachment; filename=" + new String(tbFile.getColfilename().getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
ftpUtil.connectServer("192.168.79.138", FTPClient.DEFAULT_PORT, "cms", "imis2", null);
ftpUtil.connectServer();
List<String> list = ftpUtil.getFileList("/");
for (String str : list) {
System.out.println(str);
}
InputStream inputStream = ftpUtil.downFile(new String(tbFile.getColfilename().getBytes("UTF-8"), "iso-8859-1"));
InputStream inputStream = ftpUtil.downFile(tbFile.getColfilename());
bis = new BufferedInputStream(inputStream);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
@@ -185,7 +184,7 @@ public class DownLoadController {
bos.write(buff, 0, bytesRead);
}
// 记录下载日志
// addVisitLog("下载文件" + tbFile.getColrealname() + " " + tbFile.getColfilename());
addVisitLog("下载文件" + tbFile.getColrealname() + " " + tbFile.getColfilename());
} catch (Exception e) {

View File

@@ -10,25 +10,26 @@ import com.fjy.spring.service.FileService;
import com.fjy.spring.service.HomeworkService;
import com.fjy.spring.service.LogService;
import com.fjy.spring.untils.FormatFileSizeUtil;
import com.fjy.spring.untils.FtpOperationUtil;
import com.fjy.spring.untils.GetIPAddrUtil;
import com.fjy.spring.untils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@@ -185,6 +186,7 @@ public class UpLoadController {
List<String> fileList = new ArrayList<String>();
for (MultipartFile file : files.values()) {
Homework homework = new Homework();
//管理员上传不需要传workId
if (workId != null) {
@@ -260,6 +262,18 @@ public class UpLoadController {
log.error("记录写入数据库失败");
}
try {
FtpOperationUtil ftpOperationUtil = new FtpOperationUtil();
ftpOperationUtil.connectServer();
InputStream inputStream = file.getInputStream();
String path = "/upload/" + courseName + "/" + folder + "/";
System.out.println("【目录】"+path);
boolean flag = ftpOperationUtil.uploadFile(inputStream,
tbFile.getColfilename(),path);
} catch (IOException e) {
e.printStackTrace();
}
if (!targetFile.exists()) {
try {
targetFile.createNewFile();
@@ -269,6 +283,7 @@ public class UpLoadController {
try {
file.transferTo(targetFile);
// boolean flag = ftpOperationUtil.uploadFile(tbFile.getColfilepath(),tbFile.getColfilename());
fileList.add(
request.getScheme() + "://" + request.getServerName() + ":"
+ serverProperties.getPortNum() + request.getContextPath() + "/upload/"

View File

@@ -5,7 +5,7 @@ import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
/**

View File

@@ -1,7 +1,6 @@
package com.fjy.spring.properties;
import lombok.Data;
import lombok.Getter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@@ -9,18 +8,16 @@ import org.springframework.stereotype.Component;
* @author F嘉阳
* @date 2018-05-07 19:52
*/
@Component
@ConfigurationProperties(prefix = "ftp")
@Data
public class FtpProperties {
//服务器地址名称
private String server;
private String server = "192.168.79.138";
//端口号
private int port;
private int port = 21;
//用户名称
private String username;
private String username = "cms";
//密码
private String password;
private String password = "imis2";
//工作目录
private String location;
private String location = null;
}

View File

@@ -1,27 +1,13 @@
package com.fjy.spring.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "serverproperties")
@Data
public class ServerProperties {
private String portNum;
private String filePath;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getPortNum() {
return portNum;
}
public void setPortNum(String portNum) {
this.portNum = portNum;
}
}

View File

@@ -16,7 +16,8 @@ import com.fjy.spring.properties.FtpProperties;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author F嘉阳
@@ -25,23 +26,39 @@ import org.apache.commons.net.ftp.FTPFileFilter;
public class FtpOperationUtil {
private FTPClient ftpClient;
public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;
public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;
private static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;
private static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;
/**
* 利用FtpProperties进行服务器连接
*
* @param FtpProperties 参数配置Bean类
* @throws SocketException
* @throws IOException
*/
public void connectServer(FtpProperties FtpProperties) throws SocketException,
public void connectServer() throws SocketException,
IOException {
String server = FtpProperties.getServer();
int port = FtpProperties.getPort();
String user = FtpProperties.getUsername();
String password = FtpProperties.getPassword();
String location = FtpProperties.getLocation();
FtpProperties ftpProperties = new FtpProperties();
String server = ftpProperties.getServer();
int port = ftpProperties.getPort();
String user = ftpProperties.getUsername();
String password = ftpProperties.getPassword();
String location = ftpProperties.getLocation();
connectServer(server, port, user, password, location);
}
public void connectServer(String path) throws SocketException,
IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
if (!existDirectory(path)) {
createDirectory(path);
}
ftpClient.changeWorkingDirectory(path);
FtpProperties ftpProperties = new FtpProperties();
String server = ftpProperties.getServer();
int port = ftpProperties.getPort();
String user = ftpProperties.getUsername();
String password = ftpProperties.getPassword();
String location = ftpProperties.getLocation();
connectServer(server, port, user, password, location);
}
@@ -114,9 +131,44 @@ public class FtpOperationUtil {
* @throws IOException
*/
public boolean createDirectory(String pathName) throws IOException {
pathName = new String(pathName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.makeDirectory(pathName);
}
/**
* 创建多级目录
*
* @param multiDirectory
* @return
*/
private boolean createMultiDirectory(String multiDirectory) {
boolean bool = false;
try {
String[] dirs = multiDirectory.split("/");
ftpClient.changeWorkingDirectory("/");
//按顺序检查目录是否存在,不存在则创建目录
for (int i = 1; dirs != null && i < dirs.length; i++) {
dirs[i]= new String(dirs[i].getBytes("UTF-8"), "iso-8859-1");
if (!ftpClient.changeWorkingDirectory(dirs[i])) {
if (ftpClient.makeDirectory(dirs[i])) {
if (!ftpClient.changeWorkingDirectory(dirs[i])) {
return false;
}
} else {
return false;
}
}
}
bool = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
return bool;
}
}
/**
* 在服务器上删除目录
*
@@ -125,6 +177,7 @@ public class FtpOperationUtil {
* @throws IOException
*/
public boolean removeDirectory(String path) throws IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.removeDirectory(path);
}
@@ -139,6 +192,8 @@ public class FtpOperationUtil {
public boolean removeDirectory(String path, boolean isAll)
throws IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
if (!isAll) {
return removeDirectory(path);
}
@@ -173,6 +228,9 @@ public class FtpOperationUtil {
* @throws IOException
*/
public boolean existDirectory(String path) throws IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
for (FTPFile ftpFile : ftpFileArr) {
@@ -187,6 +245,7 @@ public class FtpOperationUtil {
public boolean isExistsFile(String fileName) {
try {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
FTPFile[] file = ftpClient.listFiles(fileName);
return file.length > 0 ? true : false;
} catch (IOException e) {
@@ -203,6 +262,9 @@ public class FtpOperationUtil {
* @param path:服务器上的文件目录:/DF4
*/
public List<String> getFileList(String path) throws IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
FTPFile[] ftpFiles = ftpClient.listFiles(path);
//通过FTPFileFilter遍历只获得文件
/* FTPFile[] ftpFiles2= ftpClient.listFiles(path,new FTPFileFilter() {
@@ -223,6 +285,16 @@ public class FtpOperationUtil {
return retList;
}
/**
* 获取所有文件和目录
*
* @return
* @throws IOException
*/
public String[] list() throws IOException {
return ftpClient.listNames();
}
/**
* 删除服务器上的文件
*
@@ -231,6 +303,8 @@ public class FtpOperationUtil {
* @throws IOException
*/
public boolean deleteFile(String pathName) throws IOException {
pathName = new String(pathName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.deleteFile(pathName);
}
@@ -244,6 +318,11 @@ public class FtpOperationUtil {
public boolean uploadFile(String localFilePath, String remoteFileName)
throws IOException {
remoteFileName = new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1");
if (!existDirectory(localFilePath)) {
createDirectory(localFilePath);
ftpClient.changeWorkingDirectory(localFilePath);
}
boolean flag = false;
InputStream iStream = null;
try {
@@ -253,6 +332,35 @@ public class FtpOperationUtil {
//flag = ftpClient.storeFile(remoteFileName, bis);
flag = ftpClient.storeFile(remoteFileName, iStream);
} catch (IOException e) {
System.out.println(e.getMessage());
flag = false;
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
public boolean uploadFile(String localFilePath, String path, String remoteFileName)
throws IOException {
remoteFileName = new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
InputStream iStream = null;
try {
iStream = new FileInputStream(localFilePath);
if (path != null && path.length() != 0) {
createDirectory(path);
// 该语句必须位于创建目录之后
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
boolean flagChange = ftpClient.changeWorkingDirectory(path);
System.out.println("【目录切换】" + flagChange);
}
flag = ftpClient.storeFile(remoteFileName, iStream);
} catch (IOException e) {
System.out.println(e.getMessage());
flag = false;
return flag;
} finally {
@@ -271,6 +379,7 @@ public class FtpOperationUtil {
* @throws IOException
*/
public boolean uploadFile(String fileName) throws IOException {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
return uploadFile(fileName, fileName);
}
@@ -284,11 +393,47 @@ public class FtpOperationUtil {
*/
public boolean uploadFile(InputStream iStream, String newName)
throws IOException {
newName = new String(newName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
try {
flag = ftpClient.storeFile(newName, iStream);
} catch (IOException e) {
flag = false;
System.out.println(e.getMessage());
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
/**
* 上传文件到ftp服务器
*
* @param iStream 输入流
* @param newName 新文件名称
* @return
* @throws IOException
*/
public boolean uploadFile(InputStream iStream, String newName, String path)
throws IOException {
newName = new String(newName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
try {
if (path != null && path.length() != 0) {
createMultiDirectory(path);
// 该语句必须位于创建目录之后
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
boolean flagChange = ftpClient.changeWorkingDirectory(path);
System.out.println("【目录切换】" + flagChange);
}
flag = ftpClient.storeFile(newName, iStream);
} catch (IOException e) {
flag = false;
System.out.println(e.getMessage());
return flag;
} finally {
if (iStream != null) {
@@ -336,7 +481,7 @@ public class FtpOperationUtil {
* @throws IOException
*/
public InputStream downFile(String sourceFileName) throws IOException {
sourceFileName = sourceFileName;
sourceFileName = new String(sourceFileName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.retrieveFileStream(sourceFileName);
}
@@ -344,6 +489,7 @@ public class FtpOperationUtil {
//testUpload();
//testDownload();
FtpOperationUtil ftpUtil = new FtpOperationUtil();
ftpUtil = new FtpOperationUtil();
ftpUtil.connectServer("192.168.79.138", FTPClient.DEFAULT_PORT, "cms", "imis2", null);
//获得ftp服务器上目录名称为DF4下的所有文件名称
List<String> list = ftpUtil.getFileList("/");
@@ -356,7 +502,7 @@ public class FtpOperationUtil {
//ftpUtil.download("ERP实验1销售预测与SOP.doc", "F:\\JAVA Workspace\\Temp\\ERP实验1销售预测与SOP.doc");
String name = "ERP实验1销售预测与SOP.doc";
InputStream inputStream = ftpUtil.downFile(new String(name.getBytes("UTF-8"), "iso-8859-1"));
InputStream inputStream = ftpUtil.downFile(name);
String destination = "F:\\JAVA Workspace\\Temp\\ERP实验1销售预测与SOP.doc";
int index;

View File

@@ -8,12 +8,6 @@ server:
serverproperties:
port_num: 8080
filePath: F:\JAVA Workspace\Temp\
ftp:
server: 192.168.79.138
port: 21
username: cms
password: imis2
location: /home/ftp/cms/
spring:
thymeleaf:
prefix: classpath:/templates/

View File

@@ -1,76 +1,130 @@
package com.fjy.spring.untils;
import org.apache.commons.net.ftp.FTPClient;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static org.junit.Assert.*;
public class FtpOperationUtilTest {
@Test
public void connectServer() {
private static final String FILE_NAME = "ERP实验1销售预测与SOP.doc";
private static final String DESTINATION = "F:\\JAVA Workspace\\Temp\\upload\\ERP实验1销售预测与SOP.doc";
private static final String LOCAL_DESTINATION = "F:\\JAVA Workspace\\Temp\\ERP实验1销售预测与SOP.doc";
private static FtpOperationUtil makeConnectionFactory() {
FtpOperationUtil ftpUtil = new FtpOperationUtil();
try {
ftpUtil.connectServer();
} catch (IOException e) {
e.printStackTrace();
}
return ftpUtil;
}
private static void listFiles(FtpOperationUtil ftpUtil) throws IOException {
List<String> list = ftpUtil.getFileList("/");
for (String str : list) {
System.out.println(str);
}
}
@Test
public void connectServer1() {
public void createDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.createDirectory("创建目录");
listFiles(ftpUtil);
}
@Test
public void setFileType() {
public void removeDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.removeDirectory("创建目录");
listFiles(ftpUtil);
}
@Test
public void closeServer() {
public void removeDirectory1() throws IOException {
createDirectory();
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.removeDirectory("创建目录", true);
listFiles(ftpUtil);
}
@Test
public void changeDirectory() {
public void existDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
boolean flag = ftpUtil.existDirectory("创建目录");
System.out.println("existDirectory1:" + flag);
createDirectory();
flag = ftpUtil.existDirectory("创建目录");
System.out.println("existDirectory2:" + flag);
listFiles(ftpUtil);
}
@Test
public void createDirectory() {
public void isExistsFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
boolean flag = ftpUtil.isExistsFile(FILE_NAME);
System.out.println("isExistsFile:" + flag);
listFiles(ftpUtil);
}
@Test
public void removeDirectory() {
public void getFileList() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.getFileList("");
}
@Test
public void removeDirectory1() {
public void list() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
String[] lists = ftpUtil.list();
for (String list : lists) {
System.out.println(list);
}
}
@Test
public void existDirectory() {
public void deleteFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.deleteFile(FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void isExistsFile() {
public void uploadFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.uploadFile(DESTINATION, FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void getFileList() {
public void uploadFile2() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
File file = new File(DESTINATION);
InputStream in = new FileInputStream(file);
ftpUtil.uploadFile(in, FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void deleteFile() {
public void uploadFile3() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.uploadFile(DESTINATION,"/信息安全/", FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void uploadFile() {
}
@Test
public void uploadFile1() {
}
@Test
public void uploadFile2() {
}
@Test
public void download() {
}
@Test
public void downFile() {
public void download() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.download(FILE_NAME, DESTINATION);
listFiles(ftpUtil);
}
}