Java通过ftp进行文件上传

2020-07-19  本文已影响0人  Mracale

加入pom依赖

<!-- 加入上传文件组件 -->
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
  <dependency>
           <groupId>commons-net</groupId>
           <artifactId>commons-net</artifactId>
           <version>3.3</version>
 </dependency>

ftp上传工具类

public class FtpFileUtil {

    //ftp服务器ip地址
    private static final String FTP_ADDRESS = "127.0.0.1";
    //端口号
    private static final int FTP_PORT = 21;
    //用户名
    private static final String FTP_USERNAME = "ftpuser";
    //密码
    private static final String FTP_PASSWORD = "123";

    public  static boolean uploadFile(String ftpPath,String originFileName, InputStream input){
        boolean success = false;
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("GBK");
        try {
            int reply;
            // 连接FTP服务器
            ftp.connect(FTP_ADDRESS, 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目录生成 生成一级目录
            ftp.makeDirectory(ftpPath );
            ftp.changeWorkingDirectory(ftpPath );
            //文件上传
            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;
    }
}

文件上传

@RequestMapping(value="/upload", method = RequestMethod.POST)
    public @ResponseBody
    ResponseBean uploadImg(@RequestParam("file") MultipartFile file,
                     HttpServletRequest request) throws IOException {
        String fileName = file.getOriginalFilename();
        InputStream inputStream=file.getInputStream();
        String filePath=null;
        //文件名称生成
        String extName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString()+extName;
        //生成目录
        Calendar calendar = Calendar.getInstance();
        String ftpPath = ""+calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+(calendar.get(Calendar.DAY_OF_MONTH));
        Boolean flag= FtpFileUtil.uploadFile(ftpPath,fileName,inputStream);
        if(flag==true){
            System.out.println("ftp上传成功!");
            filePath=fileName;
        }
        String ret = "http://101.200.76.162/"+ftpPath+"/"+filePath;
        return new ResponseBean(200,"成功",ret);
    }
上一篇下一篇

猜你喜欢

热点阅读