天天看点

ftp上传-下载文件通用工具类,已实测

话不多说直接上代码

package com.springboot.demo.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.SocketException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FtpUtil {
    private final static Log logger = LogFactory.getLog(FtpUtil.class);
    private static String LOCAL_CHARSET = "UTF-8";
    // FTP协议里面,规定文件名编码为iso-8859-1
    private static String SERVER_CHARSET = "ISO-8859-1";
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static Date TODAY_TIME = new Date();

    /**
     * @return
     * @Author Mr伍
     * @Description //TODO
     * @Date 2020/4/1
     * @Param
     **/
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);              // 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);            // 登陆FTP服务器
            ftpClient.setControlEncoding("UTF-8");    // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                logger.info("未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                logger.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            logger.info("FTP的IP地址可能错误,请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }

    //判断ftp的目标文件下是否有此文件
    public static boolean isExsits(String ftpPath, String fileName, FTPClient ftpx) {

        try {
            FTPFile[] files = ftpx.listFiles(ftpPath);
            if (files != null && files.length > 0) {
                System.out.println("files size:" + files[0].getSize());
                for (FTPFile file : files
                ) {
                    String st = new String(file.getName().getBytes(LOCAL_CHARSET), SERVER_CHARSET);
                    String st1 = new String(st.getBytes(SERVER_CHARSET), LOCAL_CHARSET);
                    if (st1.equals(fileName)) {
                        return true;
                    }
                }

                return false;
            } else {
                return false;
            }
        } catch (Exception e) {
            logger.error("获取文件列表失败" + e.getMessage() + e.getClass().getName());
            return false;
            //e.printStackTrace();
        }
    }


    /**
     * 从FTP服务器下载文件
     * @param ftpHost             FTP IP地址
     * @param ftpUserName         FTP 用户名
     * @param ftpPassword         FTP用户名密码
     * @param ftpPort             FTP端口
     * @param ftpPath             FTP服务器中文件所在路径 格式: ftptest/aa
     * @param localPath           下载到本地的位置 格式:H:/download
     * @param fileName            FTP服务器上要下载的文件名称
     * @param targetFileName     本地上要的文件名称
     */
    public static String downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String localPath, String fileName, String targetFileName) {

        FTPClient ftpClient = null;
        try {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);

            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
                    "OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                LOCAL_CHARSET = "UTF-8";
            }
           if(!ftpClient.changeWorkingDirectory(ftpPath)){
               logger.error("文件夹路径不对");
              return "文件夹路径不对";
           };
            boolean flag = isExsits(ftpPath, fileName, ftpClient);

            if (!flag) {
                logger.error("文件:" + fileName + " 不存在");
                return "文件:" + fileName + " 不存在";
            }

            String f_ame = new String(fileName.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING);    //编码文件格式,解决中文文件名

            File localFile = new File(localPath + File.separatorChar + targetFileName);
            OutputStream os = new FileOutputStream(localFile);
            ftpClient.retrieveFile(f_ame, os);
            os.close();
            ftpClient.logout();

            File file=new File(System.getProperty("java.io.tmpdir")+targetFileName);
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int)file.length()];
            inputFile.read(buffer);
            inputFile.close();

            if(file.exists()){
                file.delete();//删除文件
            }
            return  new BASE64Encoder().encode(buffer);

          //  return "下载成功";
        } catch (FileNotFoundException e) {
            logger.error("没有找到" + ftpPath + "文件");
            e.printStackTrace();
        } catch (SocketException e) {
            logger.error("连接FTP失败.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("文件读取错误。");
            e.printStackTrace();
        }
        return "下载失败";
    }

    public static String uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String base64, String fileName) {
        String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String path_wl =today;
        MultipartFile file = Base64StrToImage.base64MutipartFile(base64);
        String name = fileName;
        System.err.println(name);
        FTPClient ftp = new FTPClient();
        try {
            //设置编码
            ftp.setControlEncoding("utf-8");
           ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            //连接ftp服务器

            ftp.connect(ftpHost, ftpPort);
            //响应码
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                ftp.disconnect();
            }
            //登录ftp
            boolean login = ftp.login(ftpUserName, ftpPassword);
            if (!login) {
                return "ftp服务器登录失败。请重新开始";
            }
            //设置为二进制格式
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();
            //  System.out.println("已连接"+ftp.isConnected());//查看ftp是否已连接
            logger.debug("ftp连接状态" + ftp.isConnected());

            if (!ftp.changeWorkingDirectory(path_wl)) {
                boolean b = ftp.makeDirectory(path_wl);
                if (b) {
                    ftp.changeWorkingDirectory(path_wl);
                    ftp.appendFile(name, file.getInputStream());
                }
            } else {
               ftp.appendFile(name, file.getInputStream());

            }

            logger.debug("写入成功==========");
        } catch (IOException e) {
            logger.error("文件保存失败:" + e.getMessage());
            e.printStackTrace();
            return "文件保存失败";
        } finally {
            try {

                ftp.logout();
                ftp.disconnect();
                if (ftp.isConnected()) {
                    ftp.disconnect();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "文件保存成功";

    }


    public static void main(String[] args) {
        String ftpHost = "localhost";
        String ftpUserName = "syftp";
        String ftpPassword = "1";
        int ftpPort = 21;
        String ftpPath = "\\20200403\\";
        String fileName = "房产档案索引表.jpeg";

        //上传一个文件
        try {
            File f = new File("E:\\zyb.png");
            FileInputStream inputFile = new FileInputStream(f);
            byte[] buffer = new byte[(int)f.length()];
            inputFile.read(buffer);
            inputFile.close();
            String str= new BASE64Encoder().encode(buffer);

              str="data:image/jpeg;base64,"+str;
           String flag = FtpUtil.uploadFile(ftpHost, ftpUserName, ftpPassword, ftpPort,str,fileName);
         //     System.err.println(flag);

            String tmpPath = System.getProperty("java.io.tmpdir");
            System.out.println(tmpPath);//本机临时文件夹   C:\Users\DELL\AppData\Local\Temp\
            //文件下载...输出图片base64字符
           String resoult = FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, tmpPath, fileName, "tempFile.jpeg");
          System.err.println(resoult);
          //TODO 文件是pdf时使用字符串转pdf的util
           // Base64AndPdf.Base64toPdffile("data:application/pdf;base64,"+resoult,"E:\\a13.pdf");
           //TODO 文件是图片时使用图片的util转
            MultipartFile multipartFile=Base64StrToImage.base64MutipartFile("data:application/pdf;base64,"+resoult);
            multipartFile.transferTo(Paths.get("E:\\tupian.pdf"));


            System.err.println("成功");

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
    }

 
}
           

此处自己理解,看自己的上传的文件带不带前缀

package com.springboot.demo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;


public class Base64StrToImage {
    Logger logger = LoggerFactory.getLogger(Base64StrToImage.class);
 
    public  static MultipartFile base64MutipartFileNew(String imgStr){
        try {
            String [] baseStr = imgStr.split(",");
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] b =  new byte[0];
            if(baseStr.length==2){
            b = base64Decoder.decodeBuffer(baseStr[1]);
                for(int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {
                        b[i] += 256;
                    }
                }
                return  new BASE64DecodedMultipartFile(b,baseStr[0]) ;
            }else {
                b = base64Decoder.decodeBuffer(imgStr);
                for(int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {
                        b[i] += 256;
                    }
                }
                return  new BASE64DecodedMultipartFile(b,"data:application/pdf;base64,") ;
            }

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

           

util2

package com.will.doing.util;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.MalformedURLException;
/**
 * @Author Mr伍
 * @Description //TODO 
 * @Date  2020/8/18
 * @Param 
 * @return 
 **/
public class FtpUtils {
    //ftp服务器地址
    private String hostname;
    //ftp服务器端口号默认为21
    private Integer port;
    //ftp登录账号
    private String username;
    //ftp登录密码
    private String password;

    private FTPClient ftpClient = null;

    public FTPClient getFtpClient(boolean init) {
        if (init) {
            boolean b = initFtpClient();
            if (!b) {
                System.err.println("ftp服务器连接失败");
                return null;
            }
        }
        return ftpClient;
    }

    public FtpUtils(String hostname, Integer port, String username, String password) {
        this.hostname = hostname;
        this.port = port;
        this.username = username;
        this.password = password;
    }


    /**
     * 初始化ftp服务器
     */
    private boolean initFtpClient() {
        boolean flag = false;
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        try {
            System.out.println("connecting...ftp服务器:" + this.hostname + ":" + this.port);
            ftpClient.connect(hostname, port); //连接ftp服务器
            ftpClient.login(username, password); //登录ftp服务器
            int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("connect failed...ftp服务器:" + this.hostname + ":" + this.port);
                flag = false;
            } else {
                System.out.println("connect successfu...ftp服务器:" + this.hostname + ":" + this.port);
                ftpClient.enterLocalPassiveMode();
                ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
                flag = true;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 上传文件
     *
     * @param pathname       ftp服务保存地址
     * @param fileName       上传到ftp的文件名
     * @param originfilename 待上传文件的名称(绝对地址) *
     * @return
     */
    public boolean uploadFile(String pathname, String fileName, String originfilename) {
        boolean flag = false;
        InputStream in = null;
        try {
            System.out.println("开始上传文件");
            in = new FileInputStream(new File(originfilename));
            boolean b = initFtpClient();
            if (!b) {
                System.err.println("ftp服务器连接失败");
                return false;
            }
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.storeFile(fileName, in);
            flag = true;
            System.out.println("上传文件成功");
        } catch (Exception e) {
            System.out.println("上传文件失败");
            e.printStackTrace();
        } finally {
            try {
                ftpClient.logout();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


    /**
     * 上传文件
     *
     * @param pathname ftp服务保存地址
     * @param fileName 上传到ftp的文件名
     * @param in       输入文件流
     * @return
     */
    public boolean uploadFile(String pathname, String fileName, InputStream in) {
        boolean flag = false;
        try {
            System.out.println("开始上传文件");
            boolean b = initFtpClient();
            if (!b) {
                return false;
            }
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.storeFile(fileName, in);
            flag = true;
            System.out.println("上传文件成功");
        } catch (Exception e) {
            System.out.println("上传文件失败");
            e.printStackTrace();
        } finally {
            try {
                ftpClient.logout();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    //改变目录路径
    public boolean changeWorkingDirectory(String directory) {
        boolean flag = false;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
            if (flag) {
                System.out.println("进入文件夹" + directory + " 成功!");

            } else {
                System.out.println("进入文件夹" + directory + " 失败!开始创建文件夹");
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    //创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
    public boolean CreateDirecroty(String remote) throws IOException {
        boolean success = true;
        String directory = remote + "/";
        // 如果远程目录不存在,则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            String path = "";
            String paths = "";
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                path = path + "/" + subDirectory;
                if (!existFile(path)) {
                    if (makeDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
                        System.out.println("创建目录[" + subDirectory + "]失败");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }

                paths = paths + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    //判断ftp服务器文件是否存在
    public boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }

    //创建目录
    public boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
            flag = ftpClient.makeDirectory(dir);
            if (flag) {
                System.out.println("创建文件夹" + dir + " 成功!");

            } else {
                System.out.println("创建文件夹" + dir + " 失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 下载文件 *
     *
     * @param pathname  FTP服务器文件目录 *
     * @param filename  文件名称 *
     * @param localpath 下载后的文件路径 *
     * @return
     */
    public boolean downloadFile(String pathname, String filename, String localpath) {
        boolean flag = false;
        OutputStream os = null;
        try {
            System.out.println("开始下载文件");
            boolean b = initFtpClient();
            if (!b) {
                System.err.println("连接ftp服务器失败");
                return false;
            }
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                if (filename.equalsIgnoreCase(file.getName())) {
                    File localFile = new File(localpath + "/" + file.getName());
                    os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(file.getName(), os);
                    os.close();
                }
            }
            ftpClient.logout();
            flag = true;
            System.out.println("下载文件成功");
        } catch (Exception e) {
            System.out.println("下载文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    public ByteArrayOutputStream getByteArrayOutputStream(String pathname, String filename) {
        ByteArrayOutputStream os = null;
        try {
            System.out.println("开始下载文件");
            boolean b = initFtpClient();
            if (!b) {
                System.err.println("连接ftp服务器失败");
            }
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                if (filename.equalsIgnoreCase(file.getName())) {
                    os = new ByteArrayOutputStream();
                    boolean b1 = ftpClient.retrieveFile(file.getName(), os);
                    if(b1){
                        break;
                    }else{
                        os = null;
                    }
                }
            }
            ftpClient.logout();
            System.out.println("下载文件成功");
        } catch (Exception e) {
            System.out.println("下载文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return os;
    }
/*
//测试-导入本地文件
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("C:\ins.pdf");
            fileOutputStream.write(byteArrayOutputStream.toByteArray());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
*/

    /**
     * 删除文件 *
     *
     * @param pathname FTP服务器保存目录 *
     * @param filename 要删除的文件名称 *
     * @return
     */
    public boolean deleteFile(String pathname, String filename) {
        boolean flag = false;
        try {
            System.out.println("开始删除文件");
            boolean b = initFtpClient();
            if (!b) {
                System.err.println("连接ftp服务器失败");
            }
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.dele(filename);
            ftpClient.logout();
            flag = true;
            System.out.println("删除文件成功");
        } catch (Exception e) {
            System.out.println("删除文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


}

           

扩展 ByteArrayOutputStream 转base64

try(ByteArrayOutputStream os = new ByteArrayOutputStream()) {
					docxExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(os));
					docxExporter.exportReport();
					docxExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(os));
					docxExporter.exportReport();
					FileOutputStream fileOutputStream = new FileOutputStream("D:/pri.pdf");
					fileOutputStream.write(os.toByteArray());

				DataOutputStream dos = new DataOutputStream(os);
				//boolean 1位
				dos.writeBoolean(true);
				// int 32位   4字节
				dos.writeInt(2);
				// float 32位   32字节
				dos.writeFloat(1.234354f);

				byte[] bArray = os.toByteArray();
				System.out.println("共"+bArray.length+"字节");
				for (int i = 0; i < bArray.length; ++i){
					System.out.println(bArray[i]+" ");
				}
				String	base64=new BASE64Encoder().encode(bArray);
				Base64AndPdf.base64StringToPDF(base64,"D:/pri111.pdf");

		MultipartFile multipartFile=new BASE64DecodedMultipartFile(bArray,"data:application/pdf;base64,") ;
		multipartFile.transferTo(new File("D:/pri222.pdf"));




				}
           

ftp上传-下载文件通用工具类,已实测,欢迎交流。

继续阅读