Home Java javaTutorial How to upload files to FTP in java

How to upload files to FTP in java

May 13, 2023 am 09:52 AM
java ftp

需求说明:将指定文件上传到FTP,上传成功后修改文件名。

获取文件名及路径(这里是从数据库获取,所以前面的代码就不CV了)

/**
     * 测试上传
     * @param map 从数据库获取到的文件信息 (包含文件路径FILE_PATH 文件类型FILE_TYPE等信息)
     */
     public void testUpdFtpFile(Map<String,Object> map){
         /*上传附件到FTP*/
         FileInputStream inputStream = null;
         try {
            //找到要上传的文件 
             String originfilename = "E:\\work\\files\\"+map.get("FILE_PATH").toString();
             //转成流
             inputStream = new FileInputStream(originfilename);
            //上传后的文件名+文件类型                        
            String ftpName = "上传到FTP后的文件名."+map.get("FILE_TYPE");
             boolean updFtpFile = FtpClientFile.uploadFile(ftpName,inputStream);
             if(updFtpFile){
                 //打印下日志
                 System.out.println(("=======文件已上传到FTP========"));
             }
         } catch (Exception e) {
             throw new BusinessException("附件上传失败!");
         }
     }
Copy after login

FtpClientFile工具类方法

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
 
import com.google.gson.JsonArray;
 
/**
 * ftp 上传文件
 * FTPClient commons.net 3.0.1版本
 * @author Lenovo
 *
 */
public class FtpClientFile {
    
    private static final String hostname = "10.xx.xx.xx" ;//FTP IP
    
    private static final int port = 21;//FTP 端口号
    
    private static final String username = "ftpName";//FTP 登录账号
   
    private static final String password = "ftpPsd"; //FTP 登录密码
    
    private static final String pathname = "/";//FTP 工作路径
    
    
    /**
     * 上传文件(可供Action/Controller层使用)
     * @param fileName 上传到FTP服务器后的文件名称
     * @param inputStream 输入文件流
     * @return
     */
     public static boolean uploadFile(String fileName,FileInputStream inputStream){
         
     boolean flag = false;
     FTPClient ftpClient = new FTPClient();
     //设置超时
     ftpClient.setConnectTimeout(60*60*1000);
     //设置编码
     ftpClient.setControlEncoding("UTF-8");
     try {
         //连接FTP服务器
         ftpClient.connect(hostname, port);
         //登录FTP服务器
         ftpClient.login(username, password);
         //是否成功登录FTP服务器    
         int replyCode = ftpClient.getReplyCode();
         if(!FTPReply.isPositiveCompletion(replyCode)){
             return flag;
             }
         System.out.println("===========登录FTP成功了==========");
         ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
         //切换路径 创建路径
         ftpClient.makeDirectory(pathname);
         ftpClient.changeWorkingDirectory(pathname);
         ftpClient.enterLocalPassiveMode();
         //设置缓冲
         ftpClient.setBufferSize(1024 * 1024 * 20);
         //保持连接
         ftpClient.setKeepAlive(true);
         boolean a = ftpClient.storeFile(new String(fileName.getBytes("utf-8"),"iso-8859-1"), inputStream);
         if(a){
             System.out.println("===========创建文件成功=============="+a);
                 String fileName2 = fileName+"AAA";
                 boolean status = ftpClient.rename(fileName, fileName2);
                 if(status)
                 System.out.println("===========修改文件名称成功=============="+status);
             }
         inputStream.close();
         ftpClient.logout();
         flag = true;
         } catch (Exception e) {
             e.printStackTrace();
         } finally{
             if(ftpClient.isConnected()){
                 try {
                     ftpClient.disconnect();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
         return flag;
         
     }
    
     
         
    /* public static void main(String[] args) {
         String originfilename = "C:\\Users\\Lenovo\\Desktop\\xx.txt";
         FileInputStream inputStream;
         try {
            inputStream = new FileInputStream(new File(originfilename));
            boolean a = uploadFile("xx.txt","/104/",inputStream);
            System.out.println("上传文件成功============"+a);
         } catch (FileNotFoundException e) {
            e.printStackTrace();
         }
    }*/
     
     
}
Copy after login

上传文件到FTP时 注意:是否有权限登录服务器/上传文件等操作。

默认在浏览器输入自己的ftp地址访问下看看 ftp://10.xx.xx.xx:端口号 登录看看

How to upload files to FTP in java

The above is the detailed content of How to upload files to FTP in java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles