Java代码整合linux的ftp图片服务器上传
本文章转载于我搭建的ssm博客:http://iclyj.cn/blog/articles/108.html
首先要将虚拟机的nginx和vsftp装好这个我的博客里的淘淘商城系列中有详细的步骤,这里我就不详细说了
看看我的虚拟机ip和nginx启动的情况
接着我们先写service实现的类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
package com.mmall.service.impl;
import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.util.FTPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/** * Created by lyj on 2017/8/13.
*/
@Service ( "iFileService" )
public class FileServiceImpl implements IFileService {
private Logger logger = LoggerFactory.getLogger(FileServiceImpl. class );
/**
* 图片上传
* @param file
* @param path
* @return
*/
public String upload(MultipartFile file,String path){
String fileName = file.getOriginalFilename();
//扩展名
//abc.jpg
String fileExtensionName=fileName.substring(fileName.lastIndexOf( "." )+ 1 );
String uploadFileName= UUID.randomUUID().toString()+ "." +fileExtensionName;
logger.info( "开始上传文件,上传文件的文件名:{},上传的路径:{},新文件名:{}" ,fileName,path,uploadFileName);
File fileDir= new File(path);
if (!fileDir.exists()){
fileDir.setWritable( true );
fileDir.mkdirs();
}
File targetFile= new File(path,uploadFileName);
try {
//调用
file.transferTo(targetFile);
//文件已经上传成功了
// 将targetFile上传掉我们的FTP服务器上
FTPUtil.uploadFile(Lists.newArrayList(targetFile));
//已经上传到FTP 服务器上
// 上传完之后,删除本地的upload下面的文件
targetFile.delete();
} catch (IOException e) {
logger.error( "上传文件异常" ,e);
return null ;
}
//A:abc.jpg
//B:abc.jpg
return targetFile.getName();
}
/**
* 测试方法
* @param args
*/
public static void main(String[] args) {
String fileName= "abc.jpg" ;
System.out.print(fileName.substring(fileName.lastIndexOf( "." )+ 1 ));
}
} |
这个实现的的类还要依赖一个FTPUtil类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
package com.mmall.util;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
/** * Created by lyj on 2017/8/13.
*/
public class FTPUtil {
private static final Logger logger = LoggerFactory.getLogger(FTPUtil. class );
private static String ftpIp = PropertiesUtil.getProperty( "ftp.server.ip" );
private static String ftpUser = PropertiesUtil.getProperty( "ftp.user" );
private static String ftpPass = PropertiesUtil.getProperty( "ftp.pass" );
public FTPUtil(String ip, int port,String user,String pwd){
this .ip = ip;
this .port = port;
this .user = user;
this .pwd = pwd;
}
public static boolean uploadFile (List<File> fileList) throws IOException{
FTPUtil ftpUtil= new FTPUtil(ftpIp, 21 ,ftpUser,ftpPass);
logger.info( "开始连接ftp服务器" );
boolean result=ftpUtil.uploadFile( "img" ,fileList);
logger.info( "开始连接ftp服务器,结束上传,上传结果:{}" );
return result;
}
private boolean uploadFile(String remotePath,List<File> fileList) throws IOException{
//是否传了图片
boolean uploaded= true ;
FileInputStream fis= null ;
//连接FTP服务器
if (connectService( this .ip, this .port, this .user, this .pwd)){
try {
//切换文件夹
ftpClient.changeWorkingDirectory(remotePath);
//缓冲
ftpClient.setBufferSize( 1024 );
ftpClient.setControlEncoding( "utf-8" );
//设置常量防止乱码
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//打开本地的被动模式
ftpClient.enterLocalActiveMode();
;
for (File fileItem : fileList) {
fis = new FileInputStream(fileItem);
ftpClient.storeFile(fileItem.getName(), fis);
}
} catch (IOException e){
logger.error( "上传文件异常" ,e);
uploaded = false ;
e.printStackTrace();
} finally {
fis.close();
ftpClient.disconnect();
}
}
return uploaded;
}
//判断FTP服务器是否成功连接
private boolean connectService(String ip, int port,String user,String pwd){
boolean isSuccess= false ;
ftpClient = new FTPClient();
try {
ftpClient.connect(ip);
isSuccess=ftpClient.login(user,pwd);
} catch (IOException e) {
logger.error( "连接FTP服务器失败" ,e);
}
return isSuccess;
}
private String ip;
private int port;
private String user;
private String pwd;
private FTPClient ftpClient;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this .ip = ip;
}
public int getPort() {
return port;
}
public void setPort( int port) {
this .port = port;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this .user = user;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this .pwd = pwd;
}
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this .ftpClient = ftpClient;
}
} |
到这逻辑层就已经完成了
看看控制层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@RequestMapping ( "upload.do" )
@ResponseBody
public ServerResponse upload(HttpSession session,
@RequestParam (value = "upload_file" ,required = false ) MultipartFile file, HttpServletRequest request) {
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null ) {
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员" );
}
if (iUserService.checkAdminRole(user).isSuccess()) {
String path = request.getSession().getServletContext().getRealPath( "upload" );
String targetFileName = iFileService.upload(file, path);
String url = PropertiesUtil.getProperty( "ftp.server.http.prefix" ) + targetFileName;
Map fileMap = Maps.newHashMap();
fileMap.put( "uri" , targetFileName);
fileMap.put( "url" , url);
return ServerResponse.createBySuccess(fileMap);
} else {
return ServerResponse.createByErrorMessage( "无权限操作" );
}
}
|
这里我们看到一个PropertiesUtil类,而这个类正是读取mmall.properties里的图片服务器配置的类
看看结构
mmall.properties的配置
填写自己虚拟机的ip
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
PropertiesUtil类 package com.mmall.util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
/** * Created by lyj on 2017/8/13.
*/
public class PropertiesUtil {
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil. class );
private static Properties props;
/**
* 调用文件是最先执行“static{}”
*/
static {
String fileName = "mmall.properties" ;
props = new Properties();
try {
props.load( new InputStreamReader(PropertiesUtil. class .getClassLoader().getResourceAsStream(fileName), "UTF-8" ));
} catch (IOException e) {
logger.error( "配置文件读取异常" ,e);
}
}
public static String getProperty(String key){
String value = props.getProperty(key.trim());
if (StringUtils.isBlank(value)){
return null ;
}
return value.trim();
}
public static String getProperty(String key,String defaultValue){
String value = props.getProperty(key.trim());
if (StringUtils.isBlank(value)){
value = defaultValue;
}
return value.trim();
}
} |
上述一些配置自己一个个的跟着打了一遍记得还是不太熟,得多用,一些固定的配置写法可以留着笔记以后直接调用这也是个不错的学习方法
借下来看看效果吧
图片上传成功,至于登录的是我自己本身的业务需要,只需要去掉控制层的权限验证即可跳过登录
大致的Java整合linux的vsftp图片服务器的上传代码就这么多了,不懂得可以问我
看心情解答咯!