FTP上传下载

(1)ftp连接类MultiMediaConfig.java

public class MultiMediaConfig
{

    private String id;//配置类型 1录音质检 2语音留言 3报表 4传真
    private String accWay;//访问方式 1FTP 2映射网络驱动器
    private String ftpAdd;//IP地址
    private String driverName;//网络驱动器
    private String ftpFilePath;//文件在FTP的存放路径
    private String downloadPath;//文件下载到
    private String ftpUserName;//用户名
    private String ftpPassword;//密码
    private String ftpFileIntercept; //截取长度
    private String sharedAdd;//文件服务器IP
    private String sharedUserName;//文件服务器用户名
    private String sharedPassword;//文件服务器密码
    private String sharedFilePath;//共享文件夹
    private String description;//配置描述
    private String tenantId;

}

 

(2)上传下载操作类(FTPUtil.java)
/**
 *
 * 〈FTP工具类〉
 * 〈通用方法:FTP上传和下载〉
 * @author    

 * @version   V1.00 2011-03-01[版本号, YYYY-MM-DD]
 */
public class FTPUtil
{

    private static Logger logger = Logger.getLogger(FTPUtil.class);

    /**
     * ---------------------------------------------------------------------
     * 从FTP下载所有系统资源文件到配置好的目录
     * @param mmc 配置对象<该对象可通过getMultiMediaConfig(String configId)获得>
     * @param tenantId 租户ID,系统资源按租户存放
     * @return void 将FTP服务器上的资源下载到本地指定目录下,无返回值
     * ---------------------------------------------------------------------
     */
    public static void downloadFromFTP(MultiMediaConfig mmc, String tenantId)
    {
        if (mmc != null)
        {
            /**---------------------
             * 如果本地目录不存在,创建。
             * 如果存在,删除本地文件
             *--------------------*/
            String localPath = mmc.getDownloadPath();
            String serverPath = LicenseBean.getWebApplicationContextPath();
            localPath = serverPath + localPath;
            if ( !localPath.endsWith("/"))
            {
                localPath = localPath + "/";
            }
            localPath = localPath + tenantId + "/";
            File localDir = new File(localPath);
            if ( !localDir.exists())
            {
                localDir.mkdirs();
            }
            else
            {
                File[] files = localDir.listFiles();
                if (files != null)
                {
                    for (int j = 0; j < files.length; j++ )
                    {
                        File localFile = files[j];
                        localFile.delete();
                    }
                }
            }

            /**---------------------
             * 获取远程路径及FTP连接参数
             * 将FTP上的文件下载到本地
             *--------------------*/
            String remotePath = mmc.getFtpFilePath();
            if ( !remotePath.endsWith("/"))
            {
                remotePath = remotePath + "/";
            }
            String ftpIp = mmc.getFtpAdd();
            String userName = mmc.getFtpUserName();
            String password = mmc.getFtpPassword();

            FTPClient fc = new FTPClient();
            String[] ftpInfo = ftpIp.split(":");
            try
            {
                if (ftpInfo.length > 1)
                {
                    fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
                }
                else
                {
                    fc.connect(ftpInfo[0]);
                }

                boolean login = fc.login(userName, password);
                if (login)
                {
                    String realPath = "";
                    if ("/".equals(remotePath))
                    {
                        realPath = tenantId + "/";
                    }
                    else
                    {
                        realPath = remotePath + tenantId + "/";
                    }
                    FTPFile[] ftpFiles = fc.listFiles(realPath);
                    if (ftpFiles != null)
                    {
                        FileOutputStream fos = null;
                        for (int i = 0; i < ftpFiles.length; i++ )
                        {
                            FTPFile ftpFile = ftpFiles[i];
                            String ftpFileName = ftpFile.getName();
                            if (ftpFile.isFile())
                            {
                                String localFilePath = localPath + ftpFileName;
                                fos = new FileOutputStream(localFilePath);
                                fc.setFileType(FTPClient.BINARY_FILE_TYPE);
                                fc.retrieveFile(realPath + ftpFileName, fos);
                                fos.flush();
                            }

                            if (fos != null)
                            {
                                fos.close();
                            }
                        }
                    }
                }

                fc.disconnect();
            }
            catch (Exception e)
            {
                logger.error(e.toString());
            }
        }
    }

    /**
     * ---------------------------------------------------------------------
     *〈从FTP下载指定文件到配置好的目录中〉
     * @param mmc 配置对象<该对象可通过getMultiMediaConfig(String configId)获得>
     * @param tenantId 租户ID,系统资源按租户存放
     * @param fileName 需要下载的文件
     * @return String 返回完整的本地文件名
     * ---------------------------------------------------------------------
     */
    public static String downloadFromFTP(MultiMediaConfig mmc, String tenantId,
                                         String fileName)
    {
        String localFilePath = "";
        if (mmc != null)
        {
            /**------------------------
             * 如果本地目录不存在,创建目录
             * 如果存在,删除本地同名文件
             *-----------------------*/
            String localPath = mmc.getDownloadPath();
            String serverPath = LicenseBean.getWebApplicationContextPath();
            localPath = serverPath + localPath;
            if ( !localPath.endsWith("/"))
            {
                localPath = localPath + "/";
            }
            localPath = localPath + tenantId + "/";
            File localDir = new File(localPath);
            if ( !localDir.exists())
            {
                localDir.mkdirs();
            }
            else
            {
                File[] files = localDir.listFiles();
                if (files != null)
                {
                    for (int j = 0; j < files.length; j++ )
                    {
                        File localFile = files[j];
                        if (localFile.getName().equals(fileName))
                        {
                            localFile.delete();
                        }
                    }
                }
            }

            /**---------------------
             * 获取远程路径及FTP连接参数
             * 将FTP上的文件下载到本地
             *--------------------*/
            String remotePath = mmc.getFtpFilePath();
            if ( !remotePath.endsWith("/"))
            {
                remotePath = remotePath + "/";
            }
            String ftpIp = mmc.getFtpAdd();
            String userName = mmc.getFtpUserName();
            String password = mmc.getFtpPassword();

            FTPClient fc = new FTPClient();
            String[] ftpInfo = ftpIp.split(":");
            try
            {
                if (ftpInfo.length > 1)
                {
                    fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
                }
                else
                {
                    fc.connect(ftpInfo[0]);
                }

                boolean login = fc.login(userName, password);
                if (login)
                {
                    String realPath = "";
                    if ("/".equals(remotePath))
                    {
                        realPath = tenantId + "/";
                    }
                    else
                    {
                        realPath = remotePath + tenantId + "/";
                    }
                    FTPFile[] ftpFiles = fc.listFiles(realPath);
                    if (ftpFiles != null)
                    {
                        FileOutputStream fos = null;
                        for (int i = 0; i < ftpFiles.length; i++ )
                        {
                            FTPFile ftpFile = ftpFiles[i];
                            String ftpFileName = ftpFile.getName();
                            if (ftpFile.isFile()
                                && ftpFile.getName().equals(fileName))
                            {
                                localFilePath = localPath + ftpFileName;
                                fos = new FileOutputStream(localFilePath);
                                fc.setFileType(FTPClient.BINARY_FILE_TYPE);
                                fc.retrieveFile(realPath + ftpFileName, fos);
                                fos.flush();
                            }

                            if (fos != null)
                            {
                                fos.close();
                            }
                        }
                    }
                }

                fc.disconnect();
            }
            catch (Exception e)
            {
                logger.error(e.toString());
            }
        }

        return localFilePath;
    }

    /**
     * ---------------------------------------------------------------------
     * 向FTP上传所有系统资源到配置好的目录中
     * @param mmc 配置对象<该对象可通过getMultiMediaConfig(String configId)获得>
     * @param tenantId 租户ID,系统资源按租户存放
     * @return void 将本地资源上传到FTP指定目录下,无返回值
     * ---------------------------------------------------------------------
     */
    public static void uploadToFTP(MultiMediaConfig mmc, String tenantId)
    {
        if (mmc != null)
        {
            String localPath = mmc.getDownloadPath();
            String serverPath = LicenseBean.getWebApplicationContextPath();
            localPath = serverPath + localPath;
            if ( !localPath.endsWith("/"))
            {
                localPath = localPath + "/";
            }

            localPath = localPath + tenantId;
            String remotePath = mmc.getFtpFilePath();
            if ( !remotePath.endsWith("/"))
            {
                remotePath = remotePath + "/";
            }
            FTPClient fc = new FTPClient();

            String[] ftpInfo = mmc.getFtpAdd().split(":");
            try
            {
                if (ftpInfo.length > 1)
                {
                    fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
                }
                else
                {
                    fc.connect(ftpInfo[0]);
                }

                boolean login = fc.login(mmc.getFtpUserName(),
                    mmc.getFtpPassword());

                if (login)
                {
                    /**上传前,先删除FTP上原有文件,以保持更新*/
                    String ftpPath = "";
                    if ("/".equals(remotePath))
                    {
                        ftpPath = tenantId + "/";
                    }
                    else
                    {
                        ftpPath = remotePath + tenantId + "/";
                    }
                    FTPFile[] ftpFiles = fc.listFiles(ftpPath);
                    if (ftpFiles != null)
                    {
                        for (int i = 0; i < ftpFiles.length; i++ )
                        {
                            fc.deleteFile(ftpPath + ftpFiles[i].getName());
                        }
                    }

                    /**上传本地文件到FTP*/
                    File localDir = new File(localPath);
                    File[] localFiles = localDir.listFiles();

                    if (localFiles != null)
                    {
                        FileInputStream fis = null;
                        for (int j = 0; j < localFiles.length; j++ )
                        {
                            fis = new FileInputStream(localDir + "/"
                                + localFiles[j].getName());
                            boolean change = fc.changeWorkingDirectory(ftpPath);
                            if ( !change)
                            {
                                fc.makeDirectory(ftpPath);
                                fc.changeWorkingDirectory(ftpPath);
                            }

                            fc.setFileType(FTPClient.BINARY_FILE_TYPE);
                            fc.setBufferSize(1024);
                            fc.setControlEncoding("utf-8");
                            fc.storeFile(localFiles[j].getName(), fis);

                            fis.close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.error(e.toString());
            }
        }
    }

    /**
     * ---------------------------------------------------------------------
     * 向FTP上传指定文件到配置好的目录中
     * @param mmc 配置对象<该对象可通过getMultiMediaConfig(String configId)获得>
     * @param tenantId 租户ID,系统资源按租户存放
     * @param fileName 本地文件名
     * @return void 将指定文件上传到FTP指定目录下,无返回值
     * ---------------------------------------------------------------------
     */
    public static void uploadToFTP(MultiMediaConfig mmc, String tenantId,
                                   String fileName)
    {
        if (mmc != null)
        {
            String localPath = mmc.getDownloadPath();
            String serverPath = LicenseBean.getWebApplicationContextPath();
            localPath = serverPath + localPath;
            if ( !localPath.endsWith("/"))
            {
                localPath = localPath + "/";
            }

            localPath = localPath + tenantId;
            String remotePath = mmc.getFtpFilePath();
            if ( !remotePath.endsWith("/"))
            {
                remotePath = remotePath + "/";
            }
            FTPClient fc = new FTPClient();

            String[] ftpInfo = mmc.getFtpAdd().split(":");
            try
            {
                if (ftpInfo.length > 1)
                {
                    fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
                }
                else
                {
                    fc.connect(ftpInfo[0]);
                }

                boolean login = fc.login(mmc.getFtpUserName(),
                    mmc.getFtpPassword());

                if (login)
                {
                    /**上传前,先删除FTP上原有同名文件,以保持更新*/
                    String ftpPath = "";
                    if ("/".equals(remotePath))
                    {
                        ftpPath = tenantId + "/";
                    }
                    else
                    {
                        ftpPath = remotePath + tenantId + "/";
                    }
                    FTPFile[] ftpFiles = fc.listFiles(ftpPath);
                    if (ftpFiles != null)
                    {
                        for (int i = 0; i < ftpFiles.length; i++ )
                        {
                            if (ftpFiles[i].getName().equals(fileName))
                            {
                                fc.deleteFile(ftpPath + ftpFiles[i].getName());
                            }
                        }
                    }

                    /**上传本地文件到FTP*/
                    File localDir = new File(localPath);
                    File[] localFiles = localDir.listFiles();

                    if (localFiles != null)
                    {
                        FileInputStream fis = null;
                        for (int j = 0; j < localFiles.length; j++ )
                        {
                            if (localFiles[j].getName().equals(fileName))
                            {
                                fis = new FileInputStream(
                                    localDir + "/" + localFiles[j].getName());
                                boolean change = fc.changeWorkingDirectory(ftpPath);
                                if ( !change)
                                {
                                    fc.makeDirectory(ftpPath);
                                    fc.changeWorkingDirectory(ftpPath);
                                }

                                fc.setFileType(FTPClient.BINARY_FILE_TYPE);
                                fc.setBufferSize(1024);
                                fc.setControlEncoding("utf-8");
                                fc.storeFile(localFiles[j].getName(), fis);

                                fis.close();
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.error(e.toString());
            }
        }
    }

    /**
     * ---------------------------------------------------------------------
     * 向FTP上传指定文件到配置好的目录中
     * @param mmc 配置对象<该对象可通过getMultiMediaConfig(String configId)获得>
     * @param tenantId 租户ID,系统资源按租户存放
     * @param localFile 本地文件
     * @param remoteFileName 远程文件名
     * @return void 将指定文件上传到FTP指定目录下,无返回值
     * ---------------------------------------------------------------------
     */
    public static void uploadToFTP(MultiMediaConfig mmc, String tenantId,
                                   File localFile, String remoteFileName)
    {
        if (mmc != null)
        {
            String remotePath = mmc.getFtpFilePath();
            if ( !remotePath.endsWith("/"))
            {
                remotePath = remotePath + "/";
            }
            FTPClient fc = new FTPClient();

            String[] ftpInfo = mmc.getFtpAdd().split(":");
            try
            {
                if (ftpInfo.length > 1)
                {
                    fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
                }
                else
                {
                    fc.connect(ftpInfo[0]);
                }

                boolean login = fc.login(mmc.getFtpUserName(),
                    mmc.getFtpPassword());

                if (login)
                {
                    /**上传前,先删除FTP上同名文件,以保持更新*/
                    String ftpPath = "";
                    if ("/".equals(remotePath))
                    {
                        ftpPath = tenantId + "/";
                    }
                    else
                    {
                        ftpPath = remotePath + tenantId + "/";
                    }
                    FTPFile[] ftpFiles = fc.listFiles(ftpPath);
                    if (ftpFiles != null)
                    {
                        for (int i = 0; i < ftpFiles.length; i++ )
                        {
                            if (ftpFiles[i].getName().equals(remoteFileName))
                            {
                                fc.deleteFile(ftpPath + ftpFiles[i].getName());
                            }
                        }
                    }

                    /**上传本地文件到FTP*/
                    if (localFile != null)
                    {                    
                        FileInputStream fis = new FileInputStream(
                            localFile.toString());
                        boolean change = fc.changeWorkingDirectory(ftpPath);
                        if ( !change)
                        {
                            fc.makeDirectory(ftpPath);
                            fc.changeWorkingDirectory(ftpPath);
                        }

                        fc.setFileType(FTPClient.BINARY_FILE_TYPE);
                        fc.setBufferSize(1024);
                        fc.setControlEncoding("utf-8");
                        fc.storeFile(remoteFileName, fis);
                       
                        fis.close();
                    }
                }
            }
            catch (Exception e)
            {
                logger.error("向FTP上传指定文件到配置好的目录中出错"+e.getMessage(),e);
            }
            finally
            {
                try
                {
                    fc.disconnect();
                }
                catch (IOException e)
                {
                    logger.error("关闭FTP连接出错"+e.getMessage(),e);
                }
            }
        }
    }
   
    /**
     * @author yangmj 传真发送上传文件
     * ---------------------------------------------------------------------
     * 向FTP上传指定文件到配置好的目录中
     * @param mmc 配置对象<该对象可通过getMultiMediaConfig(String configId)获得>
     * @param tenantId 租户ID,系统资源按租户存放
     * @param localFile 本地文件
     * @param remoteFileName 远程文件名
     * @return void 将指定文件上传到FTP指定目录下,无返回值
     * ---------------------------------------------------------------------
     */
    public static String uploadToFTP(MultiMediaConfig mmc, String tenantId,
                                   File localFile, String remoteFileName,String faxId)
    {
     String msg="0";
        if (mmc != null)
        {
            String remotePath = mmc.getFtpFilePath();
            if ( !remotePath.endsWith("/"))
            {
                remotePath = remotePath + "/";
            }
            FTPClient fc = new FTPClient();

            String[] ftpInfo = mmc.getFtpAdd().split(":");
            try
            {
                if (ftpInfo.length > 1)
                {
                    fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
                }
                else
                {
                    fc.connect(ftpInfo[0]);
                }

                boolean login = fc.login(mmc.getFtpUserName(),
                    mmc.getFtpPassword());

                if (login)
                {
                    /**上传前,先删除FTP上同名文件,以保持更新*/
                    String ftpPath = "";
                    if ("/".equals(remotePath))
                    {
                        ftpPath = tenantId + "/";
                    }
                    else
                    {
                        ftpPath = remotePath + tenantId + "/";
                    }
                    FTPFile[] ftpFiles = fc.listFiles(ftpPath);
                    if (ftpFiles != null)
                    {
                        for (int i = 0; i < ftpFiles.length; i++ )
                        {
                            if (ftpFiles[i].getName().equals(remoteFileName))
                            {
                                fc.deleteFile(ftpPath + ftpFiles[i].getName());
                            }
                        }
                    }

                    /**上传本地文件到FTP*/
                    if (localFile != null)
                    {
                     //检查运营参数配置的传真服务器文件存放路径是否存在
                     int isFtpFilePath = fc.cwd(ftpPath);
                        if (isFtpFilePath == 250){                      
                        }else{
                         logger.error("上传结果:"+faxId+"存放在"+remotePath+"失败,失败原因:找不到上传文件指定路径。");
                         return "0";
                        } 
                       
                        FileInputStream fis = new FileInputStream(
                            localFile.toString());
                        boolean change = fc.changeWorkingDirectory(ftpPath);
                        if ( !change)
                        {
                            fc.makeDirectory(ftpPath);
                            fc.changeWorkingDirectory(ftpPath);
                        }

                        fc.setFileType(FTPClient.BINARY_FILE_TYPE);
                        fc.setBufferSize(1024);
                        fc.setControlEncoding("utf-8");
                        fc.storeFile(remoteFileName, fis);
                       
                        fis.close();
//                        fc.logout();
                        logger.error("上传结果:"+faxId+"存放在"+remotePath+"成功。");
                        return "1";
                    }
                }else{
                 logger.error("上传结果:"+faxId+"存放在"+remotePath+"失败,失败原因:连接FTP用户名或密码不正确。");
                }
            }
            catch (Exception e)
            {
             logger.error("上传结果:"+faxId+"存放在"+remotePath+"失败,失败原因:无法连接FTP服务器。");
//                logger.error("向FTP上传指定文件到配置好的目录中出错"+e.getMessage(),e);
            }
            finally
            {
                try
                {
                    fc.disconnect();
                }
                catch (IOException e)
                {
                 logger.error("上传结果:"+faxId+"存放在"+remotePath+"失败,失败原因:关闭FTP连接出错。");
//                    logger.error("关闭FTP连接出错"+e.getMessage(),e);
                }
            }
        }
       
        return msg;
    }
   
    /**
     * ---------------------------------------------------------------------
     *〈验证文件是否存在,并且从FTP上把文件写入到临时文件夹〉
     * @param mmc 配置对象<该对象可通过getMultiMediaConfig(String configId)获得>
     * @param tenantId 租户ID,系统资源按租户存放
     * @param fileName 需要下载的文件
     * @return String 全路径
     * ---------------------------------------------------------------------
     */
    public static String validateFtpFileIsExist(MultiMediaConfig mmc,
                                                String tenantId, String fileName)
    {
        String localFilePath = "";
        try
        {
            /**------------------------
             * 如果本地目录不存在,创建目录
             * 如果存在,删除本地同名文件
             *-----------------------*/
            String localPath = mmc.getDownloadPath();
            String serverPath = LicenseBean.getWebApplicationContextPath();
            localPath = serverPath + localPath;
            if ( !localPath.endsWith("/"))
            {
                localPath = localPath + "/";
            }
            localPath = localPath + tenantId + "/";
            File localDir = new File(localPath);
            if ( !localDir.exists())
            {
                localDir.mkdirs();
            }

            /**---------------------
             * 获取远程路径及FTP连接参数
             * 将FTP上的文件下载到本地
             *--------------------*/
            String remotePath = mmc.getFtpFilePath();
            if ( !remotePath.endsWith("/"))
            {
                remotePath = remotePath + "/";
            }
            String ftpIp = mmc.getFtpAdd();
            String userName = mmc.getFtpUserName();
            String password = mmc.getFtpPassword();

            FTPClient fc = new FTPClient();
            String[] ftpInfo = ftpIp.split(":");

            if (ftpInfo.length > 1)
            {
                fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
            }
            else
            {
                fc.connect(ftpInfo[0]);
            }

            boolean login = fc.login(userName, password);
            if (login)
            {
                String realPath = "";
                if ("/".equals(remotePath))
                {
                    realPath = tenantId + "/";
                }
                else
                {
                    realPath = remotePath + tenantId + "/";
                }
                FTPFile[] ftpFiles = fc.listFiles(realPath);
                if (ftpFiles != null)
                {
                    FileOutputStream fos = null;
                    for (int i = 0; i < ftpFiles.length; i++ )
                    {
                        FTPFile ftpFile = ftpFiles[i];
                        String ftpFileName = ftpFile.getName();
                        if (ftpFile.isFile() && ftpFileName.equals(fileName))
                        {
                            localFilePath = localPath + ftpFileName;
                            fos = new FileOutputStream(localFilePath);
                            fc.setFileType(FTPClient.BINARY_FILE_TYPE);
                            fc.retrieveFile(realPath + ftpFileName, fos);
                            fos.flush();
                        }

                        if (fos != null)
                        {
                            fos.close();
                        }
                    }
                }
                fc.disconnect();
            }
        }
        catch (Exception e)
        {
            logger.error("验证FTP文件是否存在出错."+e.toString(),e);//连接或读文件出错
        }finally
        {
            return localFilePath;
        }

    }

    /**
     * ---------------------------------------------------------------------
     *〈从FTP下载指定文件到配置好的目录中,并把文件内容读到输出流中〉
     * @param mmc 配置对象<该对象可通过getMultiMediaConfig(String configId)获得>
     * @param tenantId 租户ID,系统资源按租户存放
     * @param fileName 需要下载的文件
     * @param response response
     * @return void
     * ---------------------------------------------------------------------
     */
    public static void downloadToOutputStream(MultiMediaConfig mmc,
                                              String tenantId, String fileName,
                                              HttpServletResponse response)
    {
        String localFilePath = "";
        if (mmc != null)
        {
            /**------------------------
             * 如果本地目录不存在,创建目录
             * 如果存在,删除本地同名文件
             *-----------------------*/
            String localPath = mmc.getDownloadPath();
            String serverPath = LicenseBean.getWebApplicationContextPath();
            localPath = serverPath + localPath;
            if ( !localPath.endsWith("/"))
            {
                localPath = localPath + "/";
            }
            localPath = localPath + tenantId + "/";
            File localDir = new File(localPath);
            if ( !localDir.exists())
            {
                localDir.mkdirs();
            }

            /**---------------------
             * 获取远程路径及FTP连接参数
             * 将FTP上的文件下载到本地
             *--------------------*/
            String remotePath = mmc.getFtpFilePath();
            if ( !remotePath.endsWith("/"))
            {
                remotePath = remotePath + "/";
            }
            String ftpIp = mmc.getFtpAdd();
            String userName = mmc.getFtpUserName();
            String password = mmc.getFtpPassword();

            FTPClient fc = new FTPClient();
            String[] ftpInfo = ftpIp.split(":");
            try
            {
                if (ftpInfo.length > 1)
                {
                    fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
                }
                else
                {
                    fc.connect(ftpInfo[0]);
                }

                boolean login = fc.login(userName, password);
                if (login)
                {
                    String realPath = "";
                    if ("/".equals(remotePath))
                    {
                        realPath = tenantId + "/";
                    }
                    else
                    {
                        realPath = remotePath + tenantId + "/";
                    }
                    FTPFile[] ftpFiles = fc.listFiles(realPath);
                    if (ftpFiles != null)
                    {
                        FileOutputStream fos = null;
                        for (int i = 0; i < ftpFiles.length; i++ )
                        {
                            FTPFile ftpFile = ftpFiles[i];
                            String ftpFileName = ftpFile.getName();
                            if (ftpFile.isFile()
                                && ftpFileName.equals(fileName))
                            {
                                localFilePath = localPath + ftpFileName;
                                fos = new FileOutputStream(localFilePath);
                                fc.setFileType(FTPClient.BINARY_FILE_TYPE);
                                fc.retrieveFile(realPath + ftpFileName, fos);
                                fos.flush();
                            }

                            if (fos != null)
                            {
                                fos.close();
                            }
                        }

                        File local = new File(localFilePath);
                        {
                            if (local.exists())
                            {
                                FileInputStream fis = null;
                                OutputStream out = null;
                                try
                                {
                                    response.reset();
                                    response.setContentType("application/x-download");
                                    response.setHeader("content-disposition",
                                        "attachment; filename=" + fileName);
                                    fis = new FileInputStream(local);
                                    out = response.getOutputStream();
                                    byte[] bs = new byte[1024];
                                    int len = 0;
                                    while ( (len = fis.read(bs)) > 0)
                                    {
                                        out.write(bs, 0, len);
                                    }
                                   
                                    out.flush();
                                }
                                catch (Exception e)
                                {
                                    logger.error("FTP下载文件出错," + e.toString(), e);
                                }

                                if (out != null)
                                {
                                    try
                                    {
                                        out.close();
                                    }
                                    catch (IOException e)
                                    {
                                        e.printStackTrace();
                                    }
                                }

                                if (fis != null)
                                {
                                    try
                                    {
                                        fis.close();
                                    }
                                    catch (IOException e)
                                    {
                                        e.printStackTrace();
                                    }
                                }

                            }
                            else
                            {
                                CommonUtil.returnMsg(response, "error");//文件不存在
                            }
                        }
                    }

                    fc.disconnect();
                }

            }
            catch (Exception e)
            {
                logger.error(e.toString());//连接或读文件出错
            }

        }
        else
        {
            CommonUtil.returnMsg(response, "error");//查询配置出错(可能数据库问题)
        }

    }
   
    /**
     * ---------------------------------------------------------------------
     *〈从FTP下载指定文件到配置好的目录中,并把文件内容读到输出流中,并默认保存为指定的文件名〉
     * @param mmc 配置对象<该对象可通过getMultiMediaConfig(String configId)获得>
     * @param tenantId 租户ID,系统资源按租户存放
     * @param fileName 需要下载的文件
     * @param downloadName 下载保存的文件名
     * @param response response
     * @return void
     * ---------------------------------------------------------------------
     */
    public static void downloadToOutputStream(MultiMediaConfig mmc,
                                              String tenantId, String fileName,
                                              String downloadName,
                                              HttpServletResponse response)
    {
        String localFilePath = "";
        if (mmc != null)
        {
            /**------------------------
             * 如果本地目录不存在,创建目录
             * 如果存在,删除本地同名文件
             *-----------------------*/
            String localPath = mmc.getDownloadPath();
            String serverPath = LicenseBean.getWebApplicationContextPath();
            localPath = serverPath + localPath;
            if ( !localPath.endsWith("/"))
            {
                localPath = localPath + "/";
            }
            localPath = localPath + tenantId + "/";
            File localDir = new File(localPath);
            if ( !localDir.exists())
            {
                localDir.mkdirs();
            }

            /**---------------------
             * 获取远程路径及FTP连接参数
             * 将FTP上的文件下载到本地
             *--------------------*/
            String remotePath = mmc.getFtpFilePath();
            if ( !remotePath.endsWith("/"))
            {
                remotePath = remotePath + "/";
            }
            String ftpIp = mmc.getFtpAdd();
            String userName = mmc.getFtpUserName();
            String password = mmc.getFtpPassword();

            FTPClient fc = new FTPClient();
            String[] ftpInfo = ftpIp.split(":");
            try
            {
                if (ftpInfo.length > 1)
                {
                    fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
                }
                else
                {
                    fc.connect(ftpInfo[0]);
                }

                boolean login = fc.login(userName, password);
                if (login)
                {
                    String realPath = "";
                    if ("/".equals(remotePath))
                    {
                        realPath = tenantId + "/";
                    }
                    else
                    {
                        realPath = remotePath + tenantId + "/";
                    }
                    FTPFile[] ftpFiles = fc.listFiles(realPath);
                    if (ftpFiles != null)
                    {
                        FileOutputStream fos = null;
                        for (int i = 0; i < ftpFiles.length; i++ )
                        {
                            FTPFile ftpFile = ftpFiles[i];
                            String ftpFileName = ftpFile.getName();
                            if (ftpFile.isFile()
                                && ftpFileName.equals(fileName))
                            {
                                localFilePath = localPath + ftpFileName;
                                fos = new FileOutputStream(localFilePath);
                                fc.setFileType(FTPClient.BINARY_FILE_TYPE);
                                fc.retrieveFile(realPath + ftpFileName, fos);
                                fos.flush();
                            }

                            if (fos != null)
                            {
                                fos.close();
                            }
                        }

                        File local = new File(localFilePath);
                        if (local.exists())
                        {
                            FileInputStream fis = null;
                            OutputStream out = null;
                            try
                            {
                                response.reset();
                                response.setContentType("application/x-download");
                                /**注意:此处对文件名重新编码非常重要,否则当文件名中有中文字符时,
                                 ** 可能出现一些难以理解的奇怪问题,例如显示无法打开internet站点、下载文件为未知类型等
                                 */
                                response.setHeader("content-disposition",
                                    "attachment; filename=" + new String(downloadName.getBytes("gb2312"),"iso8859-1"));
                               
                                fis = new FileInputStream(local);
                                out = response.getOutputStream();
                                byte[] bs = new byte[1024];
                                int len = 0;
                                while ( (len = fis.read(bs)) > 0)
                                {
                                    out.write(bs, 0, len);
                                }
                                out.flush();
                            }
                            catch (Exception e)
                            {
                                logger.error("FTP下载文件出错," + e.toString(), e);
                            }

                            if (out != null)
                            {
                                try
                                {
                                    out.close();
                                }
                                catch (IOException e)
                                {
                                    e.printStackTrace();
                                }
                            }

                            if (fis != null)
                            {
                                try
                                {
                                    fis.close();
                                }
                                catch (IOException e)
                                {
                                    e.printStackTrace();
                                }
                            }
                           
                            local.delete();

                        }
                        else
                        {
                            CommonUtil.returnMsg(response, "error");//文件不存在
                        }
                    }

                    fc.disconnect();
                }

            }
            catch (Exception e)
            {
                logger.error(e.toString());//连接或读文件出错
            }

        }
        else
        {
            CommonUtil.returnMsg(response, "error");//查询配置出错(可能数据库问题)
        }

    }

    /**
     *
     *〈创建租户目录〉
     * @param mmc
     * @param tenantId
     * @return boolean
     */
    public static boolean createTenantDir(MultiMediaConfig mmc, String tenantId)
    {
        boolean created = true;
        String remotePath = mmc.getFtpFilePath();
        if ( !remotePath.endsWith("/"))
        {
            remotePath = remotePath + "/";
        }
        String ftpIp = mmc.getFtpAdd();
        String userName = mmc.getFtpUserName();
        String password = mmc.getFtpPassword();

        FTPClient fc = new FTPClient();
        String[] ftpInfo = ftpIp.split(":");
        try
        {
            if (ftpInfo.length > 1)
            {
                fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
            }
            else
            {
                fc.connect(ftpInfo[0]);
            }

            boolean login = fc.login(userName, password);
            if (login)
            {
                String tenantDir = "";
                if ("/".equals(remotePath))
                {
                    tenantDir = tenantId;
                }
                else
                {
                    tenantDir = remotePath + tenantId;
                }
                fc.makeDirectory(tenantDir);
            }
        }
        catch (Exception e)
        {
            logger.error(e.toString());
            created = false;
        }
        return created;
    }

    /**
     * ---------------------------------------------------------------------
     *〈从FTP下载指定文件到配置好的目录中,并把文件内容读到输出流中〉
     * @param mmc 配置对象<该对象可通过getMultiMediaConfig(String configId)获得>
     * @param tenantId 租户ID,系统资源按租户存放
     * @param fileName 需要下载的文件
     * @param response response
     * @return void
     * ---------------------------------------------------------------------
     */
    public static void downloadToOutputStream(MultiMediaConfig mmc,
                                              String fileName,
                                              HttpServletResponse response)
    {
        String localFilePath = "";
        if (mmc != null)
        {
            /**------------------------
             * 如果本地目录不存在,创建目录
             * 如果存在,删除本地同名文件
             *-----------------------*/
            String localPath = mmc.getDownloadPath();
            String serverPath = LicenseBean.getWebApplicationContextPath();
            localPath = serverPath + localPath;
            if ( !localPath.endsWith("/"))
            {
                localPath = localPath + "/";
            }
            //localPath = localPath + tenantId + "/";
            File localDir = new File(localPath);
            if ( !localDir.exists())
            {
                localDir.mkdirs();
            }
            else
            {
                /**---------------------
                 * 获取远程路径及FTP连接参数
                 * 将FTP上的文件下载到本地
                 *--------------------*/
                String remotePath = mmc.getFtpFilePath();
                if ( !remotePath.endsWith("/"))
                {
                    remotePath = remotePath + "/";
                }

                if ("/".equals(remotePath))
                {
                    remotePath = "";
                }
                String ftpIp = mmc.getFtpAdd();
                String userName = mmc.getFtpUserName();
                String password = mmc.getFtpPassword();

                FTPClient fc = new FTPClient();
                String[] ftpInfo = ftpIp.split(":");
                try
                {
                    if (ftpInfo.length > 1)
                    {
                        fc.connect(ftpInfo[0], Integer.parseInt(ftpInfo[1]));
                    }
                    else
                    {
                        fc.connect(ftpInfo[0]);
                    }

                    boolean login = fc.login(userName, password);
                    if (login)
                    {
                        FTPFile[] ftpFiles = fc.listFiles(remotePath);
                        if (ftpFiles != null)
                        {
                            FileOutputStream fos = null;
                            for (int i = 0; i < ftpFiles.length; i++ )
                            {
                                FTPFile ftpFile = ftpFiles[i];
                                String ftpFileName = ftpFile.getName();
                                if (ftpFile.isFile()
                                    && ftpFile.getName().equals(fileName))
                                {
                                    localFilePath = localPath + ftpFileName;
                                    fos = new FileOutputStream(localFilePath);
                                    fc.setFileType(FTPClient.BINARY_FILE_TYPE);
                                    fc.retrieveFile(remotePath + ftpFileName,
                                        fos);
                                    fos.flush();
                                }

                                if (fos != null)
                                {
                                    fos.close();
                                }
                            }
                        }
                    }

                    fc.disconnect();
                }
                catch (Exception e)
                {
                    logger.error(e.toString());
                }
            }

            File local = new File(localFilePath);
            {
                if (local.exists())
                {
                    FileInputStream fis = null;
                    OutputStream out = null;
                    try
                    {
                        response.setContentType("application/x-download");
                        response.setHeader("content-disposition",
                            "attachment; filename=" + fileName);
                        fis = new FileInputStream(local);
                        out = response.getOutputStream();
                        byte[] buffer = new byte[1024];

                        while (fis.read(buffer) > 0)
                        {
                            out.write(buffer);
                            out.flush();
                        }
                    }
                    catch (Exception e)
                    {
                        logger.error(e.toString());
                    }

                }
            }
        }

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值