springboot获取FTP上音频文件,并响应流,前端audio直接调接口

目录

1. 文件就保存在本地,可以用 new File()来获取文件

2. 文件保存在FTP服务器上,可以使用ftpClient.retrieveFile(remotePath,outputStream)

小结


项目中经常用到播放一些文件,比如mp3,wav格式的一些文件,下面提供了一种直接拿到音频文件并响应给前端的一种方式,我的音频文件是存在ftp服务器上,而且ftp服务器和应用服务器是部署在一起的,文件要从ftp服务器上获取,这个可以根据实际存放的地方去拿文件。经过测试,前端只需要 <audio>标签接收就可以了,src路径直接填写接口路径,话不多说,直接上图:

1. 文件就保存在本地,可以用 new File()来获取文件

  File music = new File("C:\Users\Temp\a.mp3");

附代码:

import io.swagger.annotations.ApiImplicitParam;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/stream")
public class WavApiController {
    
    @Value("${ftpServer_url}")
    private String ftpServer_url;
    @Value("${ftpServer_audio_url}")
    private String ftpServer_audio_url;
    
    @RequestMapping("/mp3")
    @ApiImplicitParam(name = "voiceName", value = "音频文件名", paramType = "query", required = true, dataType = "String")
    public void wavStream(HttpServletRequest request, HttpServletResponse response, String voiceName){
        String database = ftpServer_url+ftpServer_audio_url;//音频文件所在的文件夹路径
        // 文件目录(偷懒没有改变量,名称,此处和FTP没关系,就是文件的绝对路径)
        // 也就是 File music = new File("C:\Users\Administrator\AppData\Local\Temp\a.mp3");
        File music = new File(database+voiceName);
        if (!music.exists()){
            System.out.println(database+"不存在 文件名为:"+voiceName+"的音频文件!");
        }
        String range=request.getHeader("Range");
        //开始下载位置
        long startByte = 0;
        //结束下载位置
        long endByte = music.length() - 1;
        //有range的话
        if (range != null && range.contains("bytes=") && range.contains("-")) {
            range = range.substring(range.lastIndexOf("=") + 1).trim();
            String ranges[] = range.split("-");
            try {
                //判断range的类型
                if (ranges.length == 1) {
                //类型一:bytes=-2343
                    if (range.startsWith("-")) {
                        endByte = Long.parseLong(ranges[0]);
                    }
                //类型二:bytes=2343-
                    else if (range.endsWith("-")) {
                        startByte = Long.parseLong(ranges[0]);
                    }
                }
                //类型三:bytes=22-2343
                else if (ranges.length == 2) {
                    startByte = Long.parseLong(ranges[0]);
                    endByte = Long.parseLong(ranges[1]);
                }
            } catch (NumberFormatException e) {
                startByte = 0;
                endByte = music.length() - 1;
            }
        }
        //要下载的长度
        long contentLength = endByte - startByte + 1;
        //文件名
        String fileName = music.getName();
        //文件类型
        String contentType = request.getServletContext().getMimeType(fileName);
        //各种响应头设置
        //参考资料:https://www.ibm.com/developerworks/cn/java/joy-down/index.html
        //坑爹地方一:看代码
        response.setHeader("Accept-Ranges", "bytes");
        //坑爹地方二:http状态码要为206
        response.setStatus(206);
        response.setContentType(contentType);
        response.setHeader("Content-Type", contentType);
        //这里文件名换你想要的,inline表示浏览器直接实用(我方便测试用的)
        //参考资料:http://hw1287789687.iteye.com/blog/2188500
        // response.setHeader("Content-Disposition", "inline;filename=test.mp3");
        response.setHeader("Content-Length", String.valueOf(contentLength));
        //坑爹地方三:Content-Range,格式为
        // [要下载的开始位置]-[结束位置]/[文件总大小]
        response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + music.length());
        BufferedOutputStream outputStream = null;
        RandomAccessFile randomAccessFile = null;
        //已传送数据大小
        long transmitted = 0;
        try {
            randomAccessFile = new RandomAccessFile(music, "r");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[4096];
            int len = 0;
            randomAccessFile.seek(startByte);
            //坑爹地方四:判断是否到了最后不足4096(buff的length)个byte这个逻辑((transmitted + len) <= contentLength)要放前面!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //不然会会先读取randomAccessFile,造成后面读取位置出错,找了一天才发现问题所在
            while ((transmitted + len) <= contentLength && (len = randomAccessFile.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
                transmitted += len;
                //停一下,方便测试,用的时候删了就行了
                Thread.sleep(10);
            }
            //处理不足buff.length部分
            if (transmitted < contentLength) {
                len = randomAccessFile.read(buff, 0, (int) (contentLength - transmitted));
                outputStream.write(buff, 0, len);
                transmitted += len;
            }
            outputStream.flush();
            response.flushBuffer();
            randomAccessFile.close();
            System.out.println("下载完毕:" + startByte + "-" + endByte + ":" + transmitted);
        } catch (ClientAbortException e) {
            System.out.println("用户停止下载:" + startByte + "-" + endByte + ":" + transmitted);
        //捕获此异常表示拥护停止下载
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2. 文件保存在FTP服务器上,可以使用ftpClient.retrieveFile(remotePath,outputStream)

ftpClient.retrieveFile(remotePath,outputStream);// 从FTP服务器上读取文件并写入到临时文件中

2.1 上面介绍的是一直文件绝对路径的情况,传文件路径过去就可以,但是经常我们的音频,视频文件是单独存放在像TFP服务器这样的Server上,我们以FTP为例,改一下上面的代码:

import io.swagger.annotations.ApiImplicitParam;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/stream")

public class WavApiController {
    
    @RequestMapping("/mp3")
    @ApiImplicitParam(name = "remotePath", value = "FTP服务器上的路径+文件名", paramType = "query", required = true, dataType = "String")
	/**
         * 本地FTP服务器:D:/FtpServer
	 * ---D:/FtpServer
	 * ------mp3(此文件夹下有文件 myMusic.mp3)
	 * ------txt(此文件夹下没有文件)
	 * -----------myMusic.mp3
	 * 
	 * 
	 * remotePath传值为:mp3/myMusic.mp3
     */
    public void wavStream(HttpServletRequest request, HttpServletResponse response, String remotePath){
		
        //========================区别-start ================================
        File music = null;
        try {
            music = File.createTempFile("tmp", remotePath.substring(remotePath.lastIndexOf(".")));
            OutputStream ops= new FileOutputStream(music);
            Boolean isSucccess = FtpUtil.retrieveFile(remotePath, ops);
            System.out.println("=====写入临时文件成功与否:====" + isSucccess);
        } catch (IOException e) {
            e.printStackTrace();
        }
	//========================区别-end ================================
		
        if (!music.exists()){
            System.out.println(database+"不存在 文件名为:"+remotePath+"的音频文件!");
        }
        String range=request.getHeader("Range");
        //开始下载位置
        long startByte = 0;
        //结束下载位置
        long endByte = music.length() - 1;
        //有range的话
        if (range != null && range.contains("bytes=") && range.contains("-")) {
            range = range.substring(range.lastIndexOf("=") + 1).trim();
            String ranges[] = range.split("-");
            try {
                //判断range的类型
                if (ranges.length == 1) {
                //类型一:bytes=-2343
                    if (range.startsWith("-")) {
                        endByte = Long.parseLong(ranges[0]);
                    }
                //类型二:bytes=2343-
                    else if (range.endsWith("-")) {
                        startByte = Long.parseLong(ranges[0]);
                    }
                }
                //类型三:bytes=22-2343
                else if (ranges.length == 2) {
                    startByte = Long.parseLong(ranges[0]);
                    endByte = Long.parseLong(ranges[1]);
                }
            } catch (NumberFormatException e) {
                startByte = 0;
                endByte = music.length() - 1;
            }
        }
        //要下载的长度
        long contentLength = endByte - startByte + 1;
        //文件名
        String fileName = music.getName();
        //文件类型
        String contentType = request.getServletContext().getMimeType(fileName);
        //各种响应头设置
        //参考资料:https://www.ibm.com/developerworks/cn/java/joy-down/index.html
        //坑爹地方一:看代码
        response.setHeader("Accept-Ranges", "bytes");
        //坑爹地方二:http状态码要为206
        response.setStatus(206);
        response.setContentType(contentType);
        response.setHeader("Content-Type", contentType);
        //这里文件名换你想要的,inline表示浏览器直接实用(我方便测试用的)
        //参考资料:http://hw1287789687.iteye.com/blog/2188500
        // response.setHeader("Content-Disposition", "inline;filename=test.mp3");
        response.setHeader("Content-Length", String.valueOf(contentLength));
        //坑爹地方三:Content-Range,格式为
        // [要下载的开始位置]-[结束位置]/[文件总大小]
        response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + music.length());
        BufferedOutputStream outputStream = null;
        RandomAccessFile randomAccessFile = null;
        //已传送数据大小
        long transmitted = 0;
        try {
            randomAccessFile = new RandomAccessFile(music, "r");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[4096];
            int len = 0;
            randomAccessFile.seek(startByte);
            //坑爹地方四:判断是否到了最后不足4096(buff的length)个byte这个逻辑((transmitted + len) <= contentLength)要放前面!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //不然会会先读取randomAccessFile,造成后面读取位置出错,找了一天才发现问题所在
            while ((transmitted + len) <= contentLength && (len = randomAccessFile.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
                transmitted += len;
                //停一下,方便测试,用的时候删了就行了
                Thread.sleep(10);
            }
            //处理不足buff.length部分
            if (transmitted < contentLength) {
                len = randomAccessFile.read(buff, 0, (int) (contentLength - transmitted));
                outputStream.write(buff, 0, len);
                transmitted += len;
            }
            outputStream.flush();
            response.flushBuffer();
            randomAccessFile.close();
            System.out.println("下载完毕:" + startByte + "-" + endByte + ":" + transmitted);
        } catch (ClientAbortException e) {
            System.out.println("用户停止下载:" + startByte + "-" + endByte + ":" + transmitted);
        //捕获此异常表示拥护停止下载
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.2 附上Ftp工具类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.zdhs.atw.common.utils._DateUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.pool2.ObjectPool;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.Assert;
import lombok.extern.slf4j.Slf4j;

/**
 * Ftp工具类
 */
@Slf4j
public class FtpUtil {

    /**
     * ftpClient连接池初始化标志
     */
    private static volatile boolean hasInit = false;
    /**
     * ftpClient连接池
     */
    private static ObjectPool<FTPClient> ftpClientPool;

    /**
     * 初始化ftpClientPool
     *
     * @param ftpClientPool
     */
    public static void init(ObjectPool<FTPClient> ftpClientPool) {
        if (!hasInit) {
            synchronized (FtpUtil.class) {
                if (!hasInit) {
                    FtpUtil.ftpClientPool = ftpClientPool;
                    hasInit = true;
                }
            }
        }
    }

//    /**
//     * 读取csv文件
//     *
//     * @param remoteFilePath 文件路径(path+fileName)
//     * @param header 列头
//     * @return
//     * @throws IOException
//     */
//    public static List<CSVRecord> readCsvFile(String remoteFilePath, String... headers) throws IOException {
//        FTPClient ftpClient = getFtpClient();
//        try (InputStream in = ftpClient.retrieveFileStream(encodingPath(remoteFilePath))) {
//            return CSVFormat.EXCEL.withHeader(headers).withSkipHeaderRecord(false)
//                    .withIgnoreSurroundingSpaces().withIgnoreEmptyLines()
//                    .parse(new InputStreamReader(in, "utf-8")).getRecords();
//        } finally {
//            ftpClient.completePendingCommand();
//            releaseFtpClient(ftpClient);
//        }
//    }

    /**
     * 按行读取FTP文件
     *
     * @param remoteFilePath 文件路径(path+fileName)
     * @return
     * @throws IOException
     */
    public static List<String> readFileByLine(String remoteFilePath) throws IOException {
        FTPClient ftpClient = getFtpClient();
        try (InputStream in = ftpClient.retrieveFileStream(encodingPath(remoteFilePath));
             BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
            return br.lines().map(line -> StringUtils.trimToEmpty(line))
                    .filter(line -> StringUtils.isNotEmpty(line)).collect(Collectors.toList());
        } finally {
            ftpClient.completePendingCommand();
            releaseFtpClient(ftpClient);
        }
    }

    /**
     * 获取指定路径下FTP文件
     *
     * @param remotePath 路径
     * @return FTPFile数组
     * @throws IOException
     */
    public static FTPFile[] retrieveFTPFiles(String remotePath) throws IOException {
        FTPClient ftpClient = getFtpClient();
        try {
            return ftpClient.listFiles(encodingPath(remotePath + "/"),
                    file -> file != null && file.getSize() > 0);
        } finally {
            releaseFtpClient(ftpClient);
        }
    }

    /**
     * 获取指定路径下FTP文件 并 写入临时文件的outputStream中
     * @param remotePath
     * @param outputStream
     * @return
     * @throws IOException
     */
    public static Boolean  retrieveFile(String remotePath, OutputStream outputStream) throws IOException {
        FTPClient ftpClient = getFtpClient();
        try {
            return ftpClient.retrieveFile(remotePath,outputStream);
        } finally {
            releaseFtpClient(ftpClient);
        }
    }

    /**
     * 获取指定路径下FTP文件名称
     *
     * @param remotePath 路径
     * @return ftp文件名称列表 和 文件操作时间
     * @throws IOException
     */
    public static Map<String, Date> retrieveFileNames(String remotePath) throws IOException {
        Map<String, Date> files = new HashMap<>();
        FTPFile[] ftpFiles = retrieveFTPFiles(remotePath);
        if (ArrayUtils.isEmpty(ftpFiles)) {
            return new HashMap<>();
        }
        //防止中文乱码
        for (FTPFile ftpFile:ftpFiles) {
            String fileName = new String(ftpFile.getName().getBytes("iso-8859-1"), "gb2312");
            Calendar fileTime = ftpFile.getTimestamp();
            Date date = fileTime.getTime();
            //Date 类型转换为 String 类型
            String time = _DateUtils.dateFormatToSecond(date);
            files.put(fileName,date);
        }
        return files;
    }

    /**
     * 编码文件路径
     */
    private static String encodingPath(String path) throws UnsupportedEncodingException {
        // FTP协议里面,规定文件名编码为iso-8859-1,所以目录名或文件名需要转码
        return new String(path.replaceAll("//", "/").getBytes("GBK"), "iso-8859-1");
    }

    /**
     * 获取ftpClient
     *
     * @return
     */
    private static FTPClient getFtpClient() {
        checkFtpClientPoolAvailable();
        FTPClient ftpClient = null;
        Exception ex = null;
        // 获取连接最多尝试3次
        for (int i = 0; i < 3; i++) {
            try {
                ftpClient = ftpClientPool.borrowObject();
                ftpClient.changeWorkingDirectory("/");
                break;
            } catch (Exception e) {
                ex = e;
            }
        }
        if (ftpClient == null) {
            throw new RuntimeException("Could not get a ftpClient from the pool", ex);
        }
        return ftpClient;
    }

    /**
     * 释放ftpClient
     */
    private static void releaseFtpClient(FTPClient ftpClient) {
        if (ftpClient == null) {
            return;
        }

        try {
            ftpClientPool.returnObject(ftpClient);
        } catch (Exception e) {
            log.error("Could not return the ftpClient to the pool", e);
            // destoryFtpClient
            if (ftpClient.isAvailable()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException io) {
                }
            }
        }
    }

    /**
     * 检查ftpClientPool是否可用
     */
    private static void checkFtpClientPoolAvailable() {
        Assert.state(hasInit, "FTP未启用或连接失败!");
    }

    /**
     * 上传Excel文件到FTP
     * @param workbook
     * @param remoteFilePath
     * @throws IOException
     */
    public static boolean uploadExcel2Ftp(Workbook workbook, String remoteFilePath)
            throws IOException {
        Assert.notNull(workbook, "workbook cannot be null.");
        Assert.hasText(remoteFilePath, "remoteFilePath cannot be null or blank.");
        FTPClient ftpClient = getFtpClient();
        try (OutputStream out = ftpClient.storeFileStream(encodingPath(remoteFilePath))) {
            workbook.write(out);
            workbook.close();
            return true;
        } finally {
            ftpClient.completePendingCommand();
            releaseFtpClient(ftpClient);
        }
    }

    /**
     * 从ftp下载excel文件
     * @param remoteFilePath
     * @param response
     * @throws IOException
     */
    public static void downloadExcel(String remoteFilePath, HttpServletResponse response)
            throws IOException {
        String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
        fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        FTPClient ftpClient = getFtpClient();
        try (InputStream in = ftpClient.retrieveFileStream(encodingPath(remoteFilePath));
             OutputStream out = response.getOutputStream()) {
            int size = 0;
            byte[] buf = new byte[10240];
            while ((size = in.read(buf)) > 0) {
                out.write(buf, 0, size);
                out.flush();
            }
        } finally {
            ftpClient.completePendingCommand();
            releaseFtpClient(ftpClient);
        }
    }

}

2.3 把FTPConfiguration 连接,登录也贴出来

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

@Slf4j
@Configuration
@ConditionalOnClass({GenericObjectPool.class, FTPClient.class})
@ConditionalOnProperty(value = "ftp.enabled", havingValue = "true")
@EnableConfigurationProperties(FTPConfiguration.FtpConfigProperties.class)
public class FTPConfiguration {

    private ObjectPool<FTPClient> pool;

    public FTPConfiguration(FtpConfigProperties props) {
        // 默认最大连接数与最大空闲连接数都为8,最小空闲连接数为0
        // 其他未设置属性使用默认值,可根据需要添加相关配置
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setTestWhileIdle(true);
        poolConfig.setMinEvictableIdleTimeMillis(60000);
        poolConfig.setSoftMinEvictableIdleTimeMillis(50000);
        poolConfig.setTimeBetweenEvictionRunsMillis(30000);
        pool = new GenericObjectPool<>(new FtpClientPooledObjectFactory(props), poolConfig);
        preLoadingFtpClient(props.getInitialSize(), poolConfig.getMaxIdle());
        // 初始化ftp工具类中的ftpClientPool
        FtpUtil.init(pool);
    }

    /**
     * 预先加载FTPClient连接到对象池中
     * @param initialSize 初始化连接数
     * @param maxIdle 最大空闲连接数
     */
    private void preLoadingFtpClient(Integer initialSize, int maxIdle) {
        if (initialSize == null || initialSize <= 0) {
            return;
        }

        int size = Math.min(initialSize.intValue(), maxIdle);
        for (int i = 0; i < size; i++) {
            try {
                pool.addObject();
            } catch (Exception e) {
                log.error("preLoadingFtpClient error...", e);
            }
        }
    }

    @PreDestroy
    public void destroy() {
        if (pool != null) {
            pool.close();
            log.info("销毁ftpClientPool...");
        }
    }

    /**
     * Ftp配置属性类,建立ftpClient时使用
     */
    @Data
    @ConfigurationProperties(prefix = "ftp")
    static class FtpConfigProperties {

        private String host;

        private int port;

        private String username;

        private String password;

        private int bufferSize = 8096;

        /**
         * 初始化连接数
         */
        private Integer initialSize = 0;

    }

    /**
     * FtpClient对象工厂类
     */
    static class FtpClientPooledObjectFactory implements PooledObjectFactory<FTPClient> {

        private FtpConfigProperties props;

        public FtpClientPooledObjectFactory(FtpConfigProperties props) {
            this.props = props;
        }

        @Override
        public PooledObject<FTPClient> makeObject() throws Exception {
            FTPClient ftpClient = new FTPClient();
            try {
                ftpClient.connect(props.getHost(), props.getPort());
                ftpClient.login(props.getUsername(), props.getPassword());
                log.info("连接FTP服务器返回码{}", ftpClient.getReplyCode());
                ftpClient.setBufferSize(props.getBufferSize());
//                ftpClient.setControlEncoding(props.getEncoding());
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();
                return new DefaultPooledObject<>(ftpClient);
            } catch (Exception e) {
                log.error("建立FTP连接失败", e);
                if (ftpClient.isAvailable()) {
                    ftpClient.disconnect();
                }
                ftpClient = null;
                throw new Exception("建立FTP连接失败", e);
            }
        }

        @Override
        public void destroyObject(PooledObject<FTPClient> p) throws Exception {
            FTPClient ftpClient = getObject(p);
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        }

        @Override
        public boolean validateObject(PooledObject<FTPClient> p) {
            FTPClient ftpClient = getObject(p);
            if (ftpClient == null || !ftpClient.isConnected()) {
                return false;
            }
            try {
                ftpClient.changeWorkingDirectory("/");
                return true;
            } catch (Exception e) {
                log.error("验证FTP连接失败::{}", ExceptionUtils.getStackTrace(e));
                return false;
            }
        }

        @Override
        public void activateObject(PooledObject<FTPClient> p) throws Exception {
        }

        @Override
        public void passivateObject(PooledObject<FTPClient> p) throws Exception {
        }

        private FTPClient getObject(PooledObject<FTPClient> p) {
            if (p == null || p.getObject() == null) {
                return null;
            }
            return p.getObject();
        }

    }

}

2.4 把配置文件中 连接FTP服务器的配置也贴出来吧

#ftp config
ftp.enabled=true
#ftp 服务器地址
ftp.host=127.0.0.1
#ftp 端口
ftp.port=21
ftp.username=admin
ftp.password=admin

小结

关于获取远程文件(例如FTP等)系统上音频文件到这里就结束了,感谢大家的阅读,希望对各位有所帮助。

另外最近在系统的学习大数据Hadoop生态圈相关知识,一些练习已经上传至github,并且会持续更新,有兴趣的小伙伴们可以互相交流下:hadoop相关练习 github地址:https://github.com/Higmin/bigdata.git

 

评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值