ftp 下载

import org.apache.commons.net.ftp.FTPClient;
/**
*
*   ftp文件下载
* @throws Exception 
* 
*/
@GetMapping("/download")
public void download(HttpServletResponse response) throws Exception { 

    String hostname="136.219.100.213";
    Integer port=21;
    String username="shop";
    String password="000";
    String remotePath="/upload/file/201710";//相对路径   /upload/image/201710
    String filename="2017032211.pdf";

    FTPClient ftp= new FTPClient();

    ftp.connect(hostname, port);// 连接FTP服务器   如果采用默认端口,可以使用            
    ftp.connect(url)的方式直接连接FTP服务器
    ftp.login(username, password);// 登录ftp
    ftp.setControlEncoding("UTF-8"); // 设置字符编码
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // 设置文件传输格式
    ftp.enterLocalPassiveMode();//防止端口没有开启
    int reply = ftp.getReplyCode();// 以2开头的都表示登陆成功
    if (FTPReply.isPositiveCompletion(reply)) {
        // 转到指定下载目录
        if (!ftp.changeWorkingDirectory(remotePath)) {
            String[] paths = StringUtils.split(remotePath, "/");
            String p = "/";
            ftp.changeWorkingDirectory(p);
            for (String s : paths) {
                p += s + "/";
                if (!ftp.changeWorkingDirectory(p)) {
                    ftp.makeDirectory(s);
                    ftp.changeWorkingDirectory(p);
                }
            }
        }
        FTPFile[] listFiles = ftp.listFiles();//列出所有的文件
        for (FTPFile ftpFile: listFiles ) {
            if (ftpFile.getName().equals(filename)) {
                if (ftpFile.isFile()) {

                    //根据文件名下载FTP服务器上的文件  

                    //第一种触发浏览器下载
                    InputStream ins=ftp.retrieveFileStream(ftpFile.getName());  
                    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();  
                    byte[] buf = new byte[1024];  
                    int bufsize = 0;  
                    while ((bufsize = ins.read(buf, 0, buf.length)) != -1) {  
                        byteOut.write(buf, 0, bufsize);  
                    }  
                    byte[] buffer = byteOut.toByteArray();  
                    byteOut.close();  
                    ins.close();  

                    String fileSuffixName=   filename.substring(filename.lastIndexOf(".")+1);
       
                    response.reset(); //清除缓存
                    response.setContentType("application/" +fileSuffixName + ";" +"charset = UTF-8"); //设置字符集和文件后缀名
                    response.setHeader("Content-Disposition","attachment; filename=" +filename); // 设置文件名称
       
                    OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  
                    toClient.write(buffer);  
                    toClient.flush();  
                    toClient.close();  

                    //第二种下载到指定目录
                    String localPath="D:"+File.separator+"program_file"+File.separator+"FTP_file";//"D:"+File.separator+"program_file"+File.separator+"FTP_file";
                    File lFile = new File(localPath);
                    lFile.mkdir(); // 如果文件所在的文件夹不存在就创建
                    FileOutputStream fos = new FileOutputStream(localPath+File.separator+filename);
                    ftp.retrieveFile(ftpFile.getName(), fos);
                    fos.flush(); // 将缓冲区中的数据全部写出
                    fos.close(); // 关闭流
                    }
                }
            } 
            ftp.logout();// 退出ftp
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        } else{
            ftp.disconnect();
        }


}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
package com.kwantler.YN_EW.service.impl; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class FilePhoto { /** * 从网络Url中下载文件 * * @param urlStr * @param fileName * @param savePath * @throws IOException */ public static void downLoadByUrl(String urlStr, String fileName, String savePath) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置超时间为3秒 conn.setConnectTimeout(5 * 1000); // 防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // 得到输入流 InputStream inputStream = conn.getInputStream(); // 获取自己数组 byte[] getData = readInputStream(inputStream); // 文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdir(); } File file = new File(saveDir + File.separator + fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } System.out.println("info:" + url + " download success"); } /** * 从输入流中获取字节数组 * * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } public static void main(String[] args) { try { downLoadByUrl( "https://www.mybiosource.com/images/tds/protocol_samples/MBS700_Antibody_Set_Sandwich_ELISA_Protocol.pdf", "ELISA.pdf", "E:/upload/protocol"); } catch (Exception e) { // TODO: handle exception } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

10000guo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值