欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

FTP文件上传下载

程序员文章站 2022-07-12 10:03:14
...

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">
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</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>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<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 = ''; 
						//清空 input file 值,以免删除后出现同名文件不可选
					});

					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文件上传下载

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;
	
    /**
     * 下载文件
     * @param ftpDirName
     * @param ftpFileName
     * @param localFileName
     * @return
     */
    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));
    		/**
    		 * OutputStream osm=resp.getOutputStream
    		 */
    		
    		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;
    	}
    }
    
    
    /**
     * 创建目录
     * @param ftpDirName
     * @return
     */
    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;
		}
    }
    
    /**
     * ftp上传文件
     * @param inputStream
     * @param ftpDirName  文件目录
     * @param fileName  文件名
     * @return true||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;
    	}
    }
    
    
    /**
     * ftp登录
     * @param ip ftp服务地址
     * @param port  端口号
     * @param username  用户名
     * @param password  密码
     * @return
     */
    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();
	}
	
	/**
	 * 销毁ftp连接
	 */
	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;
		}
	}

FTP文件上传下载

下载
http://localhost:8090/file/download?file=mybatis.xml 上传要下载的文件名即可
以上一个上传下载小例子、可根据需要自行调整代码