在做一个项目的时候需要将文件上传到FTP服务器上面,该项目使用Spring MVC,在上传的过程中使用到了Spring中的MultipartFile类,在此记录下:
(如何搭建VSFTPD服务器参见https://www.jianshu.com/p/3614585a00e9
)
1.首先是前台页面,文件的传输主要利用了表单的enctype属性,一般会取3个值
1.application/x-www-form-urlencoded::默认类型
2.multipart/form-data:上传文件时使用
3.text/plain:普通文本内容
上面中的form表单将会发送到upload.do接口中,其中文件会以二进制的形式进行传输
接下来在后台中写业务逻辑
首先是引入Maven依赖,需要导入几个Jar包
commons-net
commons-net
3.1
commons-fileupload
commons-fileupload
1.2.2
commons-io
commons-io
2.0.1
com.google.guava
guava
20.0
2.在配置文件中注入Bean
因为MultipartFile是一个接口,需要在Spring配置文件中注册其实现类CommonsMultipartResolver,注意bean的id是固定值multipartResolver
3.将文件上传到Tomcat服务器,利用MultipartFile中的transferTo进行上传
public void upload(@RequestParam(value = "upload_file") MultipartFile file){
String path = System.getProperty("catalina.home");
path = path + "\\webapps\\upload";
String fileName = file.getOriginalFilename();
String extensionName = fileName.substring(fileName.lastIndexOf("." ) + 1);
File dir = new File(path);
if (!dir.exists()){
dir.setWritable(true);
dir.mkdirs();
}
File targetFile = new File(path,fileName);
try {
file.transferTo(targetFile);
} catch (IOException e) {
e.printStackTrace();
}
}
4.然后在从Tomcat服务器上传到VSFTPD服务器,这其中需要连接到FTP服务器然后进行上传,需要先编写FTP相关工具类
(1)FTP服务器的工具类
public class FTPUtil {
private static String ip = "xx.xx.xx.xx";
private static Integer port = 21;
private static String userName = "xxxx";
private static String password = "xxxx";
private static FTPClient ftpClient;
public static boolean connection(String ip,String userName,String password){
boolean isSuccess = false;
ftpClient = new FTPClient();
try {
ftpClient.connect(ip);
isSuccess = ftpClient.login(userName,password);
} catch (IOException e) {
e.printStackTrace();
}
return isSuccess;
}
public static boolean upload(List fileList){
boolean result = upload(fileList,"test");
return result;
}
public static boolean upload(List fileList,String path){
boolean result = true;
FileInputStream fis = null;
if (connection(ip,userName,password)){
try {
ftpClient.changeWorkingDirectory(path);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
for (File item: fileList) {
fis = new FileInputStream(item);
ftpClient.storeFile(item.getName(),fis);
}
} catch (IOException e) {
e.printStackTrace();
result = false;
}finally {
try {
fis.close();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}
(2)进行上传
//上传到tomcat目录下
file.transferTo(targetFile);
//接着上传到FTP文件服务器上面
FTPUtil.upload(Lists.newArrayList(targetFile));
//最后删除tomcat下的文件
targetFile.delete();