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 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)

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.

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.

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

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles