FTP文件上传下载小demo
前端页面(layui.js)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui
</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="css/layui.css" media="all">
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>高级应用:制作一个多文件列表
</legend>
</fieldset>
<div class="layui-upload">
<button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件
</button>
<div class="layui-upload-list">
<table class="layui-table">
<thead>
<tr><th>文件名
</th>
<th>大小
</th>
<th>状态
</th>
<th>操作
</th>
</tr></thead>
<tbody id="demoList"></tbody>
</table>
</div>
<button type="button" class="layui-btn" id="testListAction">开始上传
</button>
</div>
<script src="layui.js" charset="utf-8"></script>
<script>layui.use('upload', function() {
var $ = layui.jquery,
upload = layui.upload;
var demoListView = $('#demoList'),
uploadListIns = upload.render({
elem: '#testList',
url: '/file/upload',
accept: 'file',
multiple: true,
auto: false,
bindAction: '#testListAction',
choose: function(obj) {
var files = this.files = obj.pushFile();
obj.preview(function(index, file, result) {
var tr = $(['<tr id="upload-' + index + '">', '<td>' + file.name + '</td>', '<td>' +
(file.size / 1014).toFixed(1) + 'kb</td>', '<td>等待上传</td>', '<td>', '<button class
="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>',
'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>',
</td>', '</tr>'].join(''));
tr.find('.demo-reload').on('click', function() {
obj.upload(index, file);
});
tr.find('.demo-delete').on('click', function() {
delete files[index];
tr.remove();
uploadListIns.config.elem.next()[0].value = '';
});
demoListView.append(tr);
});
},
done: function(res, index, upload) {
if(res.code == '0') {
var tr = demoListView.find('tr#upload-' + index),
tds = tr.children();
tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
tds.eq(3).html('');
return delete this.files[index];
}
this.error(index, upload);
},
error: function(index, upload) {
var tr = demoListView.find('tr#upload-' + index),
tds = tr.children();
tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
tds.eq(3).find('.demo-reload').removeClass('layui-hide');
}
});
});</script>
</body>
</html>
FTP工具类
import java
.io
.Closeable
;
import java
.io
.File
;
import java
.io
.FileOutputStream
;
import java
.io
.IOException
;
import java
.io
.InputStream
;
import java
.text
.SimpleDateFormat
;
import org
.apache
.commons
.net
.ftp
.FTPClient
;
import org
.apache
.commons
.net
.ftp
.FTPClientConfig
;
import org
.apache
.commons
.net
.ftp
.FTPFile
;
import org
.apache
.commons
.net
.ftp
.FTPReply
;
import org
.slf4j
.Logger
;
import org
.slf4j
.LoggerFactory
;
public class FTPUtils implements Closeable{
private static final Logger logger
=LoggerFactory
.getLogger(FTPUtils
.class);
private FTPClient ftp
=null
;
boolean _isLogin
=false;
public boolean downloadFile(String ftpDirName
,String ftpFileName
,String localFileName
){
try{
if("".equals(ftpDirName
))
ftpDirName
="/";
String dir
=new String(ftpDirName
.getBytes("UTF-8"),"iso-8859-1");
if(!ftp
.changeWorkingDirectory(dir
))
{
logger
.info("切换目录失败{}",dir
);
return false;
}
FTPFile
[] files
=ftp
.listFiles();
String fileName
=new String(ftpFileName
.getBytes("UTF-8"),"iso-8859-1");
Long t
=0L
;
int index
=-1;
for(int i
=0;i
<files
.length
;i
++){
if(files
[i
].getName().indexOf("_saveTime_")<0)
continue;
String name
=files
[i
].getName().substring(0,files
[i
].getName().indexOf("_saveTime_"))+files
[i
].getName().substring(files
[i
].getName().lastIndexOf("."));
logger
.info("fileName========================={}",name
);
if(!ftpFileName
.equals(name
))
continue;
String time
=files
[i
].getName().substring(files
[i
].getName().indexOf("_saveTime_"),files
[i
].getName().lastIndexOf("."));
logger
.info("time======================{}",time
);
time
=time
.substring(10);
Long timeMil
=new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").parse(time
).getTime();
if(timeMil
>t
){
t
=timeMil
;
index
=i
;
}
}
if(index
==-1){
logger
.info("文件不存在{}",fileName
);
return false;
}
FileOutputStream fos
=new FileOutputStream(new File(localFileName
));
ftp
.retrieveFile(files
[index
].getName(), fos
);
logger
.info("文件{}已从ftp下载",fileName
);
fos
.close();
logger
.info("输出流关闭成功");
this.close();
logger
.info("ftp断开连接成功");
return true;
}catch(Exception e
){
logger
.info("下载失败{}",e
);
return false;
}
}
public boolean createDir(String ftpDirName
){
String dir
= null
;
try {
dir
= new String(ftpDirName
.toString().getBytes("UTF-8"), "iso-8859-1");
if (ftp
.changeWorkingDirectory(dir
))
return true;
ftpDirName
= ftpDirName
.replaceAll("^(" + "/" + ")+", "");
ftpDirName
= ftpDirName
.replaceAll("(" + "/" + ")+$", "");
String
[] strArr
= ftpDirName
.split("/");
StringBuffer stringBuffer
= new StringBuffer();
for (String str
: strArr
) {
stringBuffer
.append("/");
stringBuffer
.append(str
);
dir
= new String(stringBuffer
.toString().getBytes("UTF-8"), "iso-8859-1");
if (ftp
.changeWorkingDirectory(dir
))
continue;
if (!ftp
.makeDirectory(dir
)) {
logger
.info("ftp创建目录失败:{}", stringBuffer
.toString());
return false;
}
logger
.info("创建ftp目录成功:{}", stringBuffer
.toString());
}
return ftp
.changeWorkingDirectory(dir
);
} catch (Exception e
) {
logger
.info("创建ftp目录失败");
return false;
}
}
public boolean uploadFile(InputStream inputStream
,String ftpDirName
,String fileName
){
logger
.info("准备上传【流】到ftp:{}/{}",ftpDirName
,fileName
);
if(fileName
==null
|| fileName
.trim().isEmpty()){
throw new RuntimeException("上传文件必须填写文件名!");
}
try{
if(!createDir(ftpDirName
)){
throw new RuntimeException("切入FTP目录失败:"+ftpDirName
);
}
ftp
.setBufferSize(1024);
ftp
.setControlEncoding("UTF-8");
FTPClientConfig conf
=new FTPClientConfig(FTPClientConfig
.SYST_NT
);
conf
.setServerLanguageCode("zh");
ftp
.setFileType(FTPClient
.BINARY_FILE_TYPE
);
String ftpFileName
=new String(fileName
.getBytes("UTF-8"),"iso-8859-1");
if(ftp
.storeFile(ftpFileName
, inputStream
)){
inputStream
.close();
logger
.info("文件上传成功:{}/{}",ftpDirName
,fileName
);
this.close();
logger
.info("ftp服务器断开连接成功");
return true;
}
return false;
}catch(Exception e
){
logger
.info("文件上传失败{}",e
);
return false;
}
}
public boolean login(String ip
,int port
,String username
,String password
){
ftp
= new FTPClient();
try {
ftp
.connect(ip
, port
);
_isLogin
= ftp
.login(username
, password
);
logger
.info(_isLogin
== true ? username
+ "ftp登录成功" :
username
+ "ftp登录失败");
int reply
= ftp
.getReplyCode();
if (!FTPReply
.isPositiveCompletion(reply
)) {
logger
.info("FTP服务器拒接连接!");
return false;
}
return true;
} catch (Exception e
) {
logger
.info("FTP服务器登录异常");
return false;
}
}
@Override
public void close() throws IOException
{
this.closeFtpConnection();
}
private void closeFtpConnection(){
_isLogin
= false;
if (ftp
!= null
) {
if (ftp
.isConnected()) {
try {
ftp
.logout();
ftp
.disconnect();
} catch (IOException e
) {
logger
.info("文件服务器退出异常:{}", e
);
}
}
}
}
}
上传下载
@PostMapping("/upload")
public Map
<String,Object> upload(MultipartFile file
) throws IllegalStateException
, IOException
{
Map
<String,Object> retMap
=new HashMap<String,Object> ();
if(file
!=null
){
String fileName
=file
.getOriginalFilename();
logger
.info("文件原名称OriginalFileName={}",fileName
);
logger
.info("文件大小Size={}byte or {}KB",file
.getSize(),file
.getSize()/1024);
FTPUtils ftp
=new FTPUtils();
boolean login
=ftp
.login("106.13.26.xxx",21, "aProduct", "xxx");
if(login
==false){
logger
.info("code", "FTP服务登录异常");
retMap
.put("code", "FTP服务登录异常");
return retMap
;
}
String dateStr
="_saveTime_"+new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date());
String beginStr
=fileName
.substring(0,fileName
.lastIndexOf("."));
String endStr
=fileName
.substring(fileName
.lastIndexOf("."));
fileName
=beginStr
+dateStr
+endStr
;
ftp
.uploadFile(file
.getInputStream(),"/aProduct",fileName
);
logger
.info("文件上传成功");
retMap
.put("code", "0");
return retMap
;
}else{
retMap
.put("code", "未获取上传文件!");
logger
.info("未获取上传文件!");
return retMap
;
}
}
@GetMapping("/download")
public Map
<String,Object> download(@RequestParam(value
="file") String file
) throws IllegalStateException
, IOException
{
Map
<String, Object> retMap
= new HashMap<String, Object>();
if (file
!= null
) {
FTPUtils ftp
= new FTPUtils();
boolean login
= ftp
.login("106.13.26.188", 21, "aProduct", "qq951210");
if (login
== false) {
logger
.info("code", "FTP服务登录异常");
retMap
.put("code", "FTP服务登录异常");
return retMap
;
}
logger
.info("fileName===================={}",file
);
boolean result
= ftp
.downloadFile("/aProduct", file
, "C:\\Users\\wanlf\\Desktop\\1\\com\\"+file
);
if (result
== false) {
logger
.info("文件下载失败");
retMap
.put("code", "1");
return retMap
;
} else {
logger
.info("文件下载成功");
retMap
.put("code", "文件下载成功");
return retMap
;
}
} else {
retMap
.put("code", "2");
logger
.info("文件名为空");
return retMap
;
}
}
下载
http://localhost:8090/file/download?file=mybatis.xml 上传要下载的文件名即可
以上一个上传下载小例子、可根据需要自行调整代码
转载请注明原文地址: https://mac.8miu.com/read-485947.html