FTP、SMB协议处理文件上传到另一台服务器

环境

 本模块依赖于SpringBoot。依赖管理使用的是Maven。

一、导入依赖

SMB协议需要的依赖

        <!--使Java支持SMB协议-->
        <dependency>
            <groupId>eu.agno3.jcifs</groupId>
            <artifactId>jcifs-ng</artifactId>
            <version>2.1.7</version>
        </dependency>

FTP协议需要的依赖

<!--Apache Commons Net-->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.8.0</version> <!-- 请使用最新的版本 -->
        </dependency>

二、文件服务器的配置

(1)关闭防火墙。

控制面板--系统和安全--Windows Defender防火墙

(2)设置共享文件夹,并添加EveryOne


 添加Everyone

 设置Everyone的权限为“读取/写入”

(3)关闭密码保护


 选择无密码保护

三、编写上传文件的工具类

package com.zkhh.util;

import jcifs.CIFSContext;
import jcifs.CIFSException;
import jcifs.config.PropertyConfiguration;
import jcifs.context.BaseContext;
import jcifs.context.SingletonContext;
import jcifs.smb.NtlmPasswordAuthenticator;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.net.URL;

public class FileUtils {
    // 将文件存储到FTP站点
    public static String storeFile(MultipartFile file){
        if(file==null||file.isEmpty()){
            return "";
        }
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        String filename = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+extension;
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect("192.168.10.61", 21);
            ftpClient.login("jinzunyue", "111");
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            String remoteFile = "/tea_admin_file/" + filename;
            InputStream inputStream = file.getInputStream();
            boolean done = ftpClient.storeFile(remoteFile, inputStream);
            inputStream.close();
            if (!done) {
                System.out.println("The file upload failed.");
                System.out.println("Server reply: " + ftpClient.getReplyString());
            }
            if (done) {
                System.out.println("The file is uploaded successfully.");
            }
        } catch (IOException ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        filename = "http://192.168.10.61:8089/images/"+filename;
        return filename;
    }

    // windows的SMB协议实现文件上传
    public static String storeFile2(MultipartFile file){
        if (file == null || file.isEmpty()) {
            return "";
        }
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        String filename = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + extension;

        String path = "smb://192.168.10.41/tea_admin_file/" + filename;

        try {
            // 有密码保护
//            CIFSContext baseContext = new BaseContext(new PropertyConfiguration(System.getProperties())).withCredentials(new NtlmPasswordAuthenticator("", "jinzunyue", "111"));
//            SmbFile smbFile = new SmbFile(path, baseContext);
            // 无密码保护
            SmbFile smbFile = new SmbFile(path);
            try (SmbFileOutputStream smbFileOutputStream = new SmbFileOutputStream(smbFile);
                 InputStream inputStream = file.getInputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    smbFileOutputStream.write(buffer, 0, len);
                }
                System.out.println("The file is uploaded successfully.");
            } catch (IOException ex) {
                System.out.println("The file upload failed.");
                System.out.println("Error: " + ex.getMessage());
                ex.printStackTrace();
            }
        } catch (IOException ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }

        filename = "http://192.168.10.41/images/" + filename;
        return filename;
    }

    // SMB协议实现文件删除
    public static boolean deleteFile(String filename) {
        String smbPath = "smb://192.168.10.41/tea_admin_file/" + filename;
        try {
            // 有密码保护
//            CIFSContext baseContext = new BaseContext(new PropertyConfiguration(System.getProperties())).withCredentials(new NtlmPasswordAuthenticator("", "jinzunyue", "111"));
//            SmbFile smbFile = new SmbFile(smbPath, baseContext);
            // 无密码保护
            SmbFile smbFile = new SmbFile(smbPath);
            if (smbFile.exists()) {
                smbFile.delete();
                System.out.println("The file is deleted successfully.");
                return true;
            } else {
                System.out.println("The file does not exist.");
                return false;
            }
        } catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
            return false;
        }
    }

    // FTP协议实现文件删除
    public static boolean deleteFile2(String filename) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect("192.168.10.61", 21);
            ftpClient.login("jinzunyue", "111");
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            String remoteFile = "/tea_admin_file/" + filename;
            boolean done = ftpClient.deleteFile(remoteFile);
            if (!done) {
                System.out.println("The file deletion failed.");
                System.out.println("Server reply: " + ftpClient.getReplyString());
            } else {
                System.out.println("The file is deleted successfully.");
            }
            return done;
        } catch (IOException ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
            return false;
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 从图片URL中获取文件名
     * @param url
     * @return
     */
    public static String getFilenameFromUrl(String url) {
        try {
            URL urlObj = new URL(url);
            String path = urlObj.getPath();
            return path.substring(path.lastIndexOf('/') + 1);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}

题外话

 该上传文件工具类在茶园项目中设计并使用。

posted @ 2023-06-25 14:16  钱有学  阅读(228)  评论(0)    收藏  举报