ftp上传与下载

import org.apache.commons.net.ftp.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ftp文件工具
 * @Author ChenWenChao
 */
@RestController
@RequestMapping("/ftp")
public class FtpUtils {
    /**ftp服务器地址*/
    private static String FTP_URL;
    /**ftp端口*/
    private static int FTP_PORT;
    /**ftp账号*/
    private static String FTP_USERNAME;
    /**ftp密码*/
    private static String FTP_PASSWORD;

    @Value("${ftp-url}")
    public void setFtpUrl(String ftpUrl){
        FTP_URL = ftpUrl;
    }
    @Value("${ftp-port}")
    public void setFtpPort(int ftpPort){
        FTP_PORT = ftpPort;
    }
    @Value("${ftp-username}")
    public void setFtpUsername(String ftpUsername){
        FTP_USERNAME = ftpUsername;
    }
    @Value("${ftp-password}")
    public void setFtpPassword(String ftpPassword){
        FTP_PASSWORD = ftpPassword;
    }

    /**
     * 向FTP服务器上传文件
     * @param path     文件存储路径(根目录开始,例如使用"/aaa"则系统会在ftp根目录下创建一个名为"aaa"的文件夹)
     * @param filename 以该文件名存储(需要加文件后缀)
     * @param file     文件
     * @return 成功返回true,否则返回false
     */
    public static boolean uploadFileToFtp(String path, String filename, MultipartFile file) {
        InputStream input = null;
        try {
            input = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean success = false;
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("GBK");
        try {
            int reply;
            //连接FTP服务器,如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.connect(FTP_URL, FTP_PORT);
            ftp.login(FTP_USERNAME, FTP_PASSWORD);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.makeDirectory(path);
            ftp.changeWorkingDirectory(path);
            ftp.storeFile(filename, input);
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    //<img src={{"/ftp/getPicture?imgPath="+d.pictureUrl}} >
    /**
     * 获取ftp服务器上的图片
     * @param request
     * @param response
     * @param imgPath   图片路径(从ftp根目录开始)
     */
    @GetMapping("/getPicture")
    public void getPicture(HttpServletRequest request, HttpServletResponse response, String imgPath) {
        FTPClient ftp = null;
        InputStream in = null;
        OutputStream os = null;
        try {
            ftp = new FTPClient();
            ftp.connect(FTP_URL, FTP_PORT);
            ftp.login(FTP_USERNAME, FTP_PASSWORD);
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.setControlEncoding("GBK");
            ftp.setBufferSize(1024 * 1024 * 10); //设置缓冲区上传速度为10M,默认为1K
            ftp.setFileType(FTP.BINARY_FILE_TYPE);//设置上传方式位字节
            ftp.enterLocalPassiveMode();//Switch to passive mode
            //下载文件 FTP协议里面,规定文件名编码为iso-8859-1,所以读取时要将文件名转码为iso-8859-1
            //如果没有设置按照UTF-8读,获取的流是空值null
            in = ftp.retrieveFileStream(new String(imgPath.getBytes("UTF-8"), "iso-8859-1"));
            String picType = imgPath.split("\\.")[1];
            BufferedImage bufImg = null;
            bufImg = ImageIO.read(in);
            os = response.getOutputStream();
            ImageIO.write(bufImg, picType, os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                    if (ftp != null) {
                        ftp.disconnect();
                        ftp = null;
                    }
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 下载ftp服务器上的文件
     * @param path      文件路径(从ftp根目录开始)
     * @param filename  文件名(记得加后缀名)
     * @param response
     * @return
     * @throws IOException
     */
    public static void downloadFtpFile(String path, String filename, HttpServletResponse response) throws IOException {
        FTPClient ftp = new FTPClient();
        // 获取文件名称
        String[] strs = filename.split("/");
        //String downloadFile = strs[strs.length - 1];
        //字符串截取
        String downloadFile = filename.substring(20);
        try {
            // 设置文件ContentType类型,这样设置,会自动判断下载文件类型
            response.setContentType("application/x-msdownload");
            // 设置文件头:最后一个参数是设置下载的文件名并编码为UTF-8
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8"));
            // 建立连接
            if (!ftp.isConnected()) {
                int reply;
                try {
                    ftp = new FTPClient();
                    ftp.connect(FTP_URL, FTP_PORT);
                    ftp.login(FTP_USERNAME, FTP_PASSWORD);
                    reply = ftp.getReplyCode();
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        ftp.disconnect();
                    }
                } catch (FTPConnectionClosedException ex) {
                    throw ex;
                } catch (Exception e) {
                    throw e;
                }
            }
            ftp.enterLocalPassiveMode();
            // 设置传输二进制文件
            int reply = ftp.getReplyCode();
            ftp.changeWorkingDirectory(path);
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                throw new IOException("failed to connect to the FTP Server:" + FTP_URL);
            }
            // 此句代码适用Linux的FTP服务器
            String newPath = new String(filename.getBytes("GBK"), "ISO-8859-1");
            // ftp文件获取文件
            InputStream is = null;
            BufferedInputStream bis = null;
            try {
                is = ftp.retrieveFileStream(newPath);
                bis = new BufferedInputStream(is);
                OutputStream out = response.getOutputStream();
                byte[] buf = new byte[1024];
                int len = 0;
                while ((len = bis.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (ftp != null) {
                        ftp.logout();
                        ftp.disconnect();
                    }
                } catch (Exception e) {
                }
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FTPConnectionClosedException e) {
            throw e;
        } catch (Exception e) {
        }
    }

    /**
     * 删除ftp服务器上的文件
     * @param filePath FTP服务器保存目录(从ftp根目录开始)
     * @param fileName 要删除的文件名称(记得加后缀名)
     * @return
     */
    public static boolean deleteFtpFile(String filePath, String fileName) {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        try {
            ftpClient.connect(FTP_URL, FTP_PORT);
            ftpClient.login(FTP_USERNAME, FTP_PASSWORD);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//文件类型为二进制文件
            ftpClient.setBufferSize(1024 * 1024 * 10);//限制缓冲区大小
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                if (ftpClient != null && ftpClient.isConnected()) {
                    try {
                        ftpClient.logout();
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("FTP服务器连接失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean flag = false;
        if (ftpClient != null) {
            try {
                ftpClient.changeWorkingDirectory(filePath);
                ftpClient.dele(fileName);
                flag = true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (ftpClient != null && ftpClient.isConnected()) {
                    try {
                        ftpClient.logout();
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 时间拼接文件名
     * @param file
     * @return 例如:"yyyy.MM.dd_HH.mm.ss_abc.docx"
     */
    public static String getFileName(MultipartFile file) {
        Date date = new Date();
        String strDateFormat = "yyyy.MM.dd_HH.mm.ss_";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        return sdf.format(date) + file.getOriginalFilename();
    }

    /**
     * 获取目录下所有的文件名称
     * @param ftpDirectory 目录名(如果不填这个参数则默认当前为根目录)
     * @return
     */
    public static List<String> getFileNameList(String ftpDirectory) {
        List<String> list = new ArrayList<String>();
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("GBK");
        try {
            //连接FTP服务器,如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.connect(FTP_URL, FTP_PORT);
            ftp.login(FTP_USERNAME, FTP_PASSWORD);// 登录
            FTPFile[] it = ftp.listFiles(ftpDirectory);
            for (int i = 0; i < it.length; i++) {
                list.add(it[i].getName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return list;
    }

}

 

配置文件application-ftp.properties

#ftp服务器地址
ftp-url=127.0.0.1
#ftp端口
ftp-port=21
#ftp账号
ftp-username=chao
#ftp密码
ftp-password=cc8929792

 

posted @ 2020-11-04 14:26  陈文超  阅读(65)  评论(0)    收藏  举报