如何从FTP上下载文件到本地

FTP 专栏收录该内容
1 篇文章 0 订阅

从FTP上获取文件并下载到本地

@Controller
@RequestMapping(value = "/demoInfo")
public class DemoController {
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;

	/**
	 * 获取接口
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getFile")
	@ResponseBody
	public void doGetFile() {

		CommJson comm = new CommJson();
		try {
			String ip = "xxx.xxx.xxx.xxx";
			String userName = "xxxxxxxxx";
			String passWord = "xxxxxx";
			String filePath = "xxxx";

			FtpClient fc = FileFTP.ftpConnection(ip, userName, passWord);
			FileFTP.ftpCd(fc, filePath);
			response.setCharacterEncoding("UTF-8");
			// word文件下载
			response.setContentType("application/msword;charset=UTF-8;");
			// zip文件下载
			// response.setContentType("application/zip;charset=UTF-8;");
			// pdf文件下载
			// response.setContentType("application/pdf;charset=UTF-8;");
			
			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("说明书.doc", "UTF-8"));
			OutputStream out = response.getOutputStream();

			FileFTP.ftpGet(fc, "说明书.doc", out);
			FileFTP.ftpClose(fc);

		} catch (Exception e) {
			comm.setError();
			comm.setMsg("获取接口列表异常");
			logger.error("doGetFile--->", e);
		}
	}

}

FTP方法:FileFTP(类),要求JDK1.7或1.7以上


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.commons.io.FileUtils;

import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpProtocolException;

public class FileFTP {

	/**
	 * 获取ftp上的文件流
	 * 
	 * @param fc
	 * @param fileName
	 * @param out
	 * @return
	 */
	public static InputStream ftpGet(FtpClient fc, String fileName, OutputStream out) {
		InputStream isSign = null;
		try {
			isSign = fc.getFileStream(fileName);
			int b;
			while ((b = isSign.read()) != -1) {
				out.write(b);
			}

			isSign.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isSign;
	}

	/**
	 * FTP链接
	 * 
	 * @param ip
	 * @param userName
	 * @param passWord
	 * @return
	 */
	public static FtpClient ftpConnection(String ip, String userName, String passWord) {
		FtpClient ftp = null;
		try {
			ftp = FtpClient.create();
			SocketAddress addr = new InetSocketAddress(ip, 21);
			ftp = FtpClient.create();
			ftp.connect(addr);
			ftp.login(userName, passWord.toCharArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ftp;
	}

	/**
	 * 切换至某路径
	 * 
	 * @param fc
	 * @param path
	 */
	public static void ftpCd(FtpClient fc, String path) {
		try {
			System.out.println("path--->" + path);
			fc.changeDirectory(path);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * FTP当前目前
	 * 
	 * @param fc
	 * @return
	 */
	public static void ftpPwd(FtpClient fc) {
		try {
			fc.changeToParentDirectory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * FTP服务关闭连接
	 * 
	 * @param fc
	 * @return
	 */
	public static boolean ftpClose(FtpClient fc) {
		try {
			fc.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 文件上传至FTP
	 * 
	 * @param fc
	 *            ftp对象
	 * @param filename
	 *            保存的文件名
	 * @param file
	 *            待上传文件
	 * @return 是否上传成功
	 */
	public static boolean ftpPut(FtpClient fc, String filename, File file) {
		FileInputStream is = null;
		OutputStream os = null;
		try {
			os = fc.putFileStream(filename);
			is = new FileInputStream(file);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				is.close();
				os.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return true;
	}

	/**
	 * 获取FTP文件至本地
	 * 
	 * @param fc
	 *            FTP对象
	 * @param filename
	 *            FTP服务器文件名
	 * @param url
	 *            本地路径含文件名
	 * @return InputStream文件流
	 */
	public static InputStream ftpGet(FtpClient fc, String fileName, String url) {
		InputStream isSign = null;
		try {
			isSign = fc.getFileStream(fileName);
			File fileSign = new File(url);
			ByteArrayOutputStream byteSignInfo = new ByteArrayOutputStream();
			int chSign;
			while ((chSign = isSign.read()) != -1) {
				byteSignInfo.write(chSign);
			}
			byte[] dataSign = byteSignInfo.toByteArray();
			FileUtils.writeByteArrayToFile(fileSign, dataSign);
			isSign.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isSign;
	}

	/**
	 * 判断Ftp目录是否存在,如果不存在则创建目录
	 * 
	 * @param ftpClient
	 * @param dir
	 * @return
	 */
	public static boolean isDirExist(FtpClient ftpClient, String dir) {
		boolean flag = false;
		System.out.println("dir--->" + dir);
		try {
			try {
				ftpClient.changeDirectory(dir);
			} catch (FtpProtocolException e1) {
				try {
					ftpClient.makeDirectory(dir);
					flag = true;
				} catch (FtpProtocolException e) {
					e.printStackTrace();
				}
			}

		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return flag;
	}

}

然后打开路径:http://localhost:8080/demoService/demo/demoInfo/getFile

就可以把FTP上的《说明书.doc》文件下载到本地

  • 1
    点赞
  • 0
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值