title: 图片上传之FTP服务器
tags: Spring,Spring FTP,commons-net
前言
通常图片、音频、视频都会占用大量的存储空间,我们在做后台开发的时候,会将这些文件存储到单独的FTP服务器,这样可以方便管理,并且很好的分离开业务。前面讲过图片上传的服务器的代码,这里将图片不保存到本地服务器,而是上传到FTP服务器。
Spring项目,添加FTP支持
Apache下面有个开源项目 commons-net,这个项目主要封装了各种网络协议的功能包括:FTP,SMTP,POP3,TELNET,ECHO等。
添加maven支持
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.5</version>
</dependency>
properties配置
ftp.host=com.xxx.ftp
ftp.port=21
ftp.username=ftpusername
ftp.password=ftppassword
ftp.savePath=ftppath/
ftp.downloadUrl=http://xxxxx/ftppath/
上述为ftp服务器的地址、端口、用户名、文件保存路径、文件访问路径等信息,将这些信息放入props-ftp.properties,然后放入spring 的配置place-holder中
<context:property-placeholder location="classpath*:conf/props-*.properties"/>
将properties映射到model
@Component
public class FtpConfig {
@Value("${ftp.host}")
private String host;
@Value("${ftp.port}")
private int port;
@Value("${ftp.username}")
private String username;
@Value("${ftp.password}")
private String password;
@Value("${ftp.savePath}")
private String savePath;
@Value("${ftp.downloadUrl}")
private String downloadUrl;
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
Controller代码
/**
* Created by cody on 2016/12/26.
* <p>
* 附件上传、获取Controller
*/
@Controller
@RequestMapping(value = {"upload", "attachment"})
public class AttachmentController {
private static final Logger logger = Logger.getLogger(AttachmentController.class);
@Autowired
private AttachmentService attachmentService;
@RequestMapping(value = {"image", "file", "bin", "apk"}, method = RequestMethod.POST)
@ResponseBody
public Object uploadBinary(@RequestParam("file") MultipartFile file, HttpServletRequest request,
@Autowired ApiMessage apiMessage) {
try {
attachmentService.saveToFtp(file, apiMessage);
} catch (Exception e) {
logger.debug(e);
}
return apiMessage;
}
}
Service 代码
/**
* Created by cody on 2016/12/27.
*
* 附件、图片、logo service
*
*/
@Service
public class AttachmentService {
private static final Logger logger = Logger.getLogger(AttachmentService.class);
@Autowired
private FtpConfig ftpConfig;
@Autowired
private AttachmentDao attachmentDao;
/**
* 保存文件到ftp
* @param file
* @param apiMessage
*/
public void saveToFtp(MultipartFile file, ApiMessage apiMessage) {
//无上传的文件
if(file == null || file.isEmpty()){
apiMessage.setSuccess(false);
apiMessage.setStatusCode(ERROR_NO_FILE);
apiMessage.setMessage("未发现文件");
return;
}
//获取文件名
String originalName = file.getOriginalFilename();
String ext = originalName.substring(originalName.lastIndexOf('.'));
String outFileName = UUID.randomUUID() + ext;
FTPClient ftp = new FTPClient();
try{
ftp.connect(ftpConfig.getHost(),ftpConfig.getPort());
boolean loginSuccess = ftp.login(ftpConfig.getUsername(),ftpConfig.getPassword());
if(loginSuccess){//登录成功
int reply = ftp.getReplyCode();
if(FTPReply.isPositiveCompletion(reply)){
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.setRemoteVerificationEnabled(false);
//切换到目标目录
// String dir = ftp.printWorkingDirectory();
ftp.changeWorkingDirectory(ftpConfig.getSavePath());
//上传文件
boolean success = ftp.storeFile(outFileName,file.getInputStream());
if(!success){
apiMessage.setSuccess(false);
apiMessage.setMessage("上传到ftp失败");
return;
}
String url = ftpConfig.getDownloadUrl() + outFileName;
TAttachment attachment = new TAttachment();
attachment.setUrl(url);
//将URL保存到Attachment数据库,并返回
attachmentDao.add(attachment);
apiMessage.setResult(attachment);
}else{//没有应答
apiMessage.setSuccess(false);
apiMessage.setStatusCode(ERROR_FTP_NO_REPLY);
}
}else{//登录失败
logger.error("ftp登录失败");
apiMessage.setSuccess(false);
apiMessage.setStatusCode(ERROR_FTP_LOGIN_ERROR);
}
}catch (Exception e){
logger.error(e);
apiMessage.setSuccess(false);
apiMessage.setStatusCode(ERROR_UPLOAD_EXCEPTION);
}finally {
try {
ftp.logout();
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}