java从ftp上传下载文件到本地

package com.cqyy.oa.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Data
public class FtpConfig {
    //ftp服务器ip地址
    @Value("${FTP_ADDRESS}")
    private String FTP_ADDRESS;
    //端口号
    @Value("${FTP_PORT}")
    private  int FTP_PORT;
    //用户名
    @Value("${FTP_USERNAME}")
    private  String FTP_USERNAME;
    //密码
    @Value("${FTP_PASSWORD}")
    private  String FTP_PASSWORD;
    //图片路径
    @Value("${FTP_BASEPATH}")
    private String FTP_BASEPATH;
}

 

上传下载工具类

package com.cqyy.oa.common.util;
import com.cqyy.oa.config.FtpConfig;
import lombok.Data;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

import static com.sun.xml.internal.ws.api.message.Packet.State.ServerResponse;

/**
 * Created by hhl
 */
@SuppressWarnings("all")
public class FtpFileUtil {
    public  static boolean uploadFile(FtpConfig ftpConfig, String originFileName, InputStream input){
        boolean success = false;
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("GBK");
        try {
            int reply;
            ftp.connect(ftpConfig.getFTP_ADDRESS(), ftpConfig.getFTP_PORT());// 连接FTP服务器
            ftp.login(ftpConfig.getFTP_USERNAME(), ftpConfig.getFTP_PASSWORD());// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.makeDirectory(ftpConfig.getFTP_BASEPATH());
            ftp.changeWorkingDirectory(ftpConfig.getFTP_BASEPATH() );
            ftp.storeFile(originFileName,input);
            input.close();
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }

    /**
     * Description: 从FTP服务器下载文件
     * @param host FTP服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName 要下载的文件名
     * @param localPath 下载后保存到本地的路径
     * @return
     *//*
    public static boolean downloadFile(HttpServletResponse response,FtpConfig ftpConfig, String fileName, String localPath) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(ftpConfig.getFTP_ADDRESS(), ftpConfig.getFTP_PORT());
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(ftpConfig.getFTP_USERNAME(), ftpConfig.getFTP_PASSWORD());// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(ftpConfig.getFTP_BASEPATH());// 转移到FTP服务器目录
            ftp.retrieveFile()
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());
                    OutputStream is = new FileOutputStream(localFile);
                    byte[] b = new byte[1024];
                    int length;
                    while ((length = inputStream.read(b)) > 0) {
                        os.write(b, 0, length);
                    }
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }

            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }*/


    /**
     * 从ftp中下载文件
     * @param path
     *           ftp文件路径
     * @param fileName
     *           ftp文件名
     * @return
     */
    public static InputStream downFile(FtpConfig ftpConfig,String path, String fileName) {
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(ftpConfig.getFTP_ADDRESS(), ftpConfig.getFTP_PORT());
            // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(ftpConfig.getFTP_USERNAME(), ftpConfig.getFTP_PASSWORD());// 登录
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 说明连接成功
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return null;
            }
            ftp.changeWorkingDirectory(path);// 转移到FTP服务器目录
            ftp.setControlEncoding("GBK");
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                // 解决下载文件 中文名字乱码
                /*String gbk = new String(ff.getName().getBytes("UTF-8"), "GBK");*/
                if (ff.getName().equals(fileName)) {
                    /*String name = new String(ff.getName().getBytes("iso-8859-1"), "UTF-8");*/
                    return ftp.retrieveFileStream(new String(ff.getName().getBytes("gbk"),"iso-8859-1"));
                }
            }
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return null;
    }

}
FtpFileController
package com.cqyy.oa.web.controller;
import com.cqyy.oa.common.base.BaseResponse;
import com.cqyy.oa.common.util.FtpFileUtil;
import com.cqyy.oa.config.FtpConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * Created by nishuai on 2017/12/26.
 */
@Api(tags = "上传下载文档")
@CrossOrigin
@Controller
public class FtpFileUploadController {

    @Autowired
    private FtpConfig ftpConfig;

    //ftp处理文件上传
    @RequestMapping(value="/ftpuploadimg", method = RequestMethod.POST)
    public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,
                                          HttpServletRequest request) throws IOException {
        String fileName = file.getOriginalFilename();
        InputStream inputStream=file.getInputStream();
        String filePath=null;
        Boolean flag= FtpFileUtil.uploadFile(ftpConfig,fileName,inputStream);
        if(flag==true){
            System.out.println("ftp上传成功!");
            filePath=fileName;
        }

        return  filePath;  //该路径图片名称,前端框架可用ngnix指定的路径+filePath,即可访问到ngnix图片服务器中的图片
    }

    /**
     * 文件流
     *
     * @param response
     * @return
     */
    @ApiOperation(value = "下载文件接口",notes = "下载文件")
    @RequestMapping(value = "stream/{fileName}/{ext}", method = RequestMethod.GET)
    public String thumbnail(HttpServletResponse response,HttpServletRequest request,@PathVariable("fileName") String filename,@PathVariable("ext") String ext) {
        /*FtpFileUtil.downFile(ftpConfig, ftpConfig.getFTP_BASEPATH(), "hhl.png");*/
        // 1.设置文件ContentType类型,自动判断下载文件类型
        response.setContentType("multipart/form-data");
        // ftp文件名
        /*String filename = "*.xls";*/
         filename=filename + "." + ext;
        /*int status = 0;
        byte b[] = new byte[1024];*/
        // 输入流
        InputStream in = null;
        // 输出流
        ServletOutputStream out = null;
        try {
            // 获取ftp中需要下载的文件名
            response.setHeader("content-disposition", "attachment; filename="
                    + new String(filename.getBytes("utf-8"), "iso-8859-1"));
            // 从FtpUtil工具类中将ftp的地址和文件名传到‘in’中
            in = FtpFileUtil.downFile(ftpConfig , ftpConfig.getFTP_BASEPATH(), filename);
            // 服务器响应获取输出文件
            out = response.getOutputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = in.read(b)) > 0) {
                out.write(b, 0, length);
            }
            /*while (status != -1) {
                status = in.read(b);
                // out.write(b);
                // System.err.println(status);
                if (status != -1)
                    out.write(b, 0, status);
            }*/

            // 要求将缓冲区的数据输出到接收方。
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null)
                try {
                    // 关闭输入流
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (out != null)
                try {
                    // 关闭输出流
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        return null;
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值