JAVA上传文件到FTP上

 

添加maven

        <!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

 

UploadUtils.java

import org.apache.commons.lang.RandomStringUtils;


public class UploadUtils {


    /**
     * 36个小写字母和数字
     */
    public static final char[] N36_CHARS = { '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
            'x', 'y', 'z' };


    public static String generateFilename(String path, String ext) {
        return path + RandomStringUtils.random(8, N36_CHARS) + "." + ext;
    }




}

 

ftp工具类

FtpUtils.java  

package com.test.cms.ftp;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
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.FTPReply;

import java.io.*;
import java.net.SocketException;

public class FtpUtils {


    private static final String IP="FTP的IP地址";

    /**
     * ftp端口 默认21
     */
    private static final Integer PORT=21;

    /**
     * ftp用户名
     */
    private static final String USERNAME="k";

    /**
     * ftp密码
     */
    private static final String PASSWORD="k";

    /**
     * 上传的固定路径,可以为空
     */
    private static final String PATH="";

    /**
     * 编码。默认UTF-8
     */
    private static final String ENCODING="UTF-8";

    /**
     *  文件上传
     * @param path 上传的路径
     * @param ext 文件扩展名
     * @param in
     * @return
     */
    public static String storeByExt(String path, String ext, InputStream in) {
        String filename = UploadUtils.generateFilename(path, ext);
        store(filename, in);
        return filename;
    }


    /**
     * 上传文件到ftp
     * @param remote 文件名称
     * @param in
     * @return
     */
    private static int store(String remote, InputStream in) {
        try {
            FTPClient ftp = getClient();
            if (ftp != null) {
                String filename = PATH + remote;
                String name = FilenameUtils.getName(filename);
                String path = FilenameUtils.getFullPath(filename);
                //切换到path路径下
                if (!ftp.changeWorkingDirectory(path)) {
                    //path路径不存在。进行创建
                    String[] ps = StringUtils.split(path, '/');
                    String p = "/";
                    ftp.changeWorkingDirectory(p);
                    for (String s : ps) {
                        p += s + "/";
                        if (!ftp.changeWorkingDirectory(p)) {
                            //判断 s 文件夹是否存在,不存在才会执行这行代码
                            ftp.makeDirectory(s);
                            ftp.changeWorkingDirectory(p);
                        }
                    }
                }
                ftp.storeFile(name, in);
                ftp.logout();
                ftp.disconnect();
            }
            in.close();
            return 0;
        } catch (SocketException e) {
            e.printStackTrace();
            return 3;
        } catch (IOException e) {
            e.printStackTrace();
            return 4;
        }
    }

    /**
     * 获取ftp连接客户端
     * @return
     * @throws SocketException
     * @throws IOException
     */
    private static FTPClient getClient() throws SocketException, IOException {
        FTPClient ftp = new FTPClient();
        ftp.addProtocolCommandListener(new PrintCommandListener(
                new PrintWriter(System.out)));
        ftp.setDefaultPort(PORT);
        ftp.connect(IP);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            System.out.println("FTP server refused connection: {}");
            ftp.disconnect();
            return null;
        }
        if (!ftp.login(USERNAME, PASSWORD)) {
            System.out.println("FTP server refused login: {}, user: {}");
            ftp.logout();
            ftp.disconnect();
            return null;
        }
        ftp.setControlEncoding(ENCODING);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        return ftp;
    }


}

 

 

控制器,调用方法

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class TestController {


    /**
     * 上传文件到ftp方法
     * @param file
     * @return
     */
    @RequestMapping(value = "/saveFile")
    @ResponseBody
    public String saveFile(MultipartFile file){
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            CloseableHttpClient client = httpClientBuilder.build();
            //获取扩展名
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
            //ftp存放的文件夹路径 以“/”开头和结尾,路径不要包含中文,不存在的文件夹会进行创建,储存的文件名随机生成
            String uploadPath="/awdfffeee1/202010/";
            //上传后的文件路径
            String fileUrl = FtpUtils.storeByExt(uploadPath, ext, file.getInputStream());
            return fileUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static void main(String[] args) {

    }
}

 

posted @ 2020-10-16 16:43  yvioo  阅读(911)  评论(0编辑  收藏  举报