首先说一下ftp的特点是:传输速度快,适用于上传大文件,适用于局域网络。
直奔主题,这里采用apache提供的网络包,commons-net.jar。我用的3.3。
ftp上传需要ftp服务器。这里描述客户端的实现。
spring 文件上传这一块就不做描述
直接代码(上传)
@RequestMapping(value = "/uploadConfigFile")
@ResponseBody
public void uploadConfigFile(@RequestParam("uploadFile") MultipartFile uploadFile){
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("120.120.120.156",21);
ftpClient.login("user1", "user1");
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//设置上传目录
ftpClient.changeWorkingDirectory("/GOS_CAS/RECONVERT/cas_config_reconvert");
String fileName = new String(uploadFile.getOriginalFilename().getBytes("utf-8"),"iso-8859-1");
FTPFile[] fs = ftpClient.listFiles();
if (fs!=null && fs.length>0) {
for(int i=0;i<fs.length;i++){
if (fs[i].getName().equals(fileName)) {
ftpClient.deleteFile(fs[i].getName());
break;
}
}
}
OutputStream os = ftpClient.appendFileStream(fileName);
byte[] bytes = new byte[1024];
InputStream is = uploadFile.getInputStream();
// 开始复制 其实net已经提供了上传的函数,但是我想可能是我这个版本有点问题 //ftpClient.storeFile("", fis);
// 于是我自己write出去了,其实我想都是一样的效果,在这里告诉大家这两种方式都能实现
int c;
// 暂未考虑中途终止的情况
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
os.flush();
is.close();
os.close();
RestoreConfiguration restoreConfiguration = new RestoreConfiguration();
restoreConfiguration.setStrName(fileName);
getServiceStub().restoreConfiguration(restoreConfiguration);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
下载
@RequestMapping(value = "/downloadConfigFile")
public void downloadConfigFile(HttpServletResponse response,@RequestParam("fileName")String fileName) {
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
FTPClient ftpClient = new FTPClient();
try {
int reply;
ftpClient.connect("120.120.120.156",21);
ftpClient.login("user1", "user1");
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return;
}
ftpClient.changeWorkingDirectory("/GOS_CAS/BACKUP/cas_config_backup");//转移到FTP服务器目录
FTPFile[] fs = ftpClient.listFiles();
for(int i=0;i<fs.length;i++){
if(fs[i].getName().equals(fileName)){
String saveAsFileName = new String(fs[i].getName().getBytes("UTF-8"), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment;fileName="+saveAsFileName);
OutputStream os = response.getOutputStream();
ftpClient.retrieveFile(fs[i].getName(), os);
os.flush();
os.close();
break;
}
}
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
}
以上就简单的自己总结了一下,希望对各位有点帮助,同时不足之处希望大神斧正