spring boot的ftp上传下载

本文介绍了一个名为FtpUtils2的Java类,该类提供了与FTP服务器进行交互的功能,包括文件上传和下载。通过使用Spring框架,FtpUtils2能够处理MultipartFile类型的文件上传请求,并返回文件的下载链接。此外,它还实现了从FTP服务器下载文件到本地的功能。
package com.zjqy.qbcs.common;


import com.zjqy.qbcs.util.DownloadFile;
import com.zjqy.qbcs.util.FtpUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.MalformedURLException;
import java.util.UUID;
@RestController
@Service
public class FtpUtils2 {
    private final Logger logger = LoggerFactory.getLogger(FtpUtils.class);
    //ftp服务器地址
    @Value("${ftp.ip}")
    private String hostname;
    @Value("${ftp.port}")
    private int port;
    @Value("${ftp.username}")
    private String username;
    @Value("${ftp.password}")
    private String password;
    @Value("${server.port}")
    private int bdPort;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    /**
     * 本地临时目录 需要 定期清空
     */
    @Value("${benDi.localDirectory}")
    private String localDirectory;
    @Value("${fileUpload.file_url_head}")
    private String file_url_head;
    @Value("${fileUpload.home_pic_url_directory}")
    private String home_pic_url_directory;
    @Value("${fileUpload.goods_pic_url_directory}")
    private String goods_pic_url_directory;
    @Value("${fileUpload.report_url_directory}")
    private String report_url_directory;
    @Value("${fileUpload.train_video_directory}")
    private String train_video_directory;
    @Value("${fileUpload.file_download_directory}")
    private String file_download_directory;
    @Value("${fileUpload.model_default_img}")
    private String model_default_img;
    @Value("${fileUpload.tool_default_img}")
    private String tool_default_img;
    @Value("${fileUpload.train_default_img}")
    private String train_default_img;
    @Value("${fileUpload.report_default_img}")
    private String report_default_img;
    public FTPClient ftpClient = null;

    /**
     * 初始化ftp服务器
     */
    public void initFtpClient() {
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        try {
            //System.out.println("connecting...ftp服务器:"+this.hostname+":"+this.port);
            ftpClient.connect(hostname, port); //连接ftp服务器
            ftpClient.login(username, password); //登录ftp服务器
            int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
            logger.trace(String.valueOf(replyCode));
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                logger.trace("connect failed...ftp服务器:" + this.hostname + ":" + this.port);
            }
            logger.trace("connect successfu...ftp服务器:" + this.hostname + ":" + this.port);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     * @param file  文件
     * @param type  目录类型
     * @return
     */
    @RequestMapping("/uploadFileAll")
    public String uploadFileAll(MultipartFile file,int type) {
        try {
            if (file != null) {
                String ftpFilePath = getType(type);
                String originalFilename = file.getOriginalFilename();//文件名字
                String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
                String newFileName = UUID.randomUUID() + suffix;
                File a=new File(localDirectory);
                if (a.exists()) {
                    a.mkdirs();
                }
                File fil = new File(localDirectory + newFileName);
                if (fil.exists()) {
                    fil.mkdirs();
                }
                    file.transferTo(fil);
                boolean b = uploadToFtp(fil, ftpFilePath);
                if (b) {
                    System.out.println("上传ftp成功");
                    //删除本地的
                    fil.delete();
                }
                StringBuffer stringBuffer = new StringBuffer();
//                stringBuffer.append("localhost:");
//                stringBuffer.append(bdPort);
//                stringBuffer.append(contextPath);
                stringBuffer.append("/downloadFileAllAndQuery");
                stringBuffer.append("?type=");
                stringBuffer.append(type);
                stringBuffer.append("&fileName=");
                stringBuffer.append(newFileName);
                System.err.println("接口地址为:" + stringBuffer.toString());
                return stringBuffer.toString();
            } else {
                System.out.println("文件是空的");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     * @param type  ftp文件所在目录位置
     * @param fileName  文件名称
     * @return
     */
    @RequestMapping("/downloadFileAllAndQuery")
    public ResponseEntity<InputStreamResource> downloadFileAllAndQuery(int type, String fileName) {
        String path = null;
        String f = null;
        try {
            String ftpFilePath=getType(type);
            initFtpClient();
            ftpClient.changeWorkingDirectory(ftpFilePath);
            ftpClient.enterLocalPassiveMode();
            if (ftpClient != null) {
                FTPFile[] files = ftpClient.listFiles();
                for (FTPFile file : files) {
                    f = new String(file.getName().getBytes("iso-8859-1"), "utf-8");//防止乱码
                    System.out.println(f);
                    if (f.equals(fileName)) {  //aa44ce45-0fc3-40c7-ac2c-23b5568fd7f9.mp4   7961ad9c-78e8-463a-8619-03f05fdf9622.jpeg
                        path = localDirectory + File.separatorChar + f;
                        File localFile = new File(path);
                        OutputStream os = new FileOutputStream(localFile);
                        ftpClient.retrieveFile(f, os);
                        os.close();
                        ftpClient.logout();
                        break;
                    }
                }
                DownloadFile downloadFile = new DownloadFile();
                return downloadFile.downloadFile(path, f);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private String getType(int type) {
        String ftpFilePath=null;
        if (type==1){
            ftpFilePath=file_url_head;
        }else if (type==2){
            ftpFilePath=home_pic_url_directory;
        }else if (type==3){
            ftpFilePath=goods_pic_url_directory;
        }else if (type==4){
            ftpFilePath=report_url_directory;
        }else if (type==5){
            ftpFilePath=train_video_directory;
        }else if (type==6){
            ftpFilePath=file_download_directory;
        }else if (type==7){
            ftpFilePath=model_default_img;
        }else if (type==8){
            ftpFilePath=tool_default_img;
        }else if (type==9){
            ftpFilePath=train_default_img;
        }else if (type==10){
            ftpFilePath=report_default_img;
        }
        return ftpFilePath;
    }

    private boolean uploadToFtp(File file,String ftpFilePath){
        try {
            initFtpClient();
            ftpClient.changeWorkingDirectory(ftpFilePath);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.storeFile(file.getName(), new FileInputStream(file));
            System.out.println(file.getName());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

让类可以读取的数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值