FtpServiceImpl.java 6.2 KB
Newer Older
1 2 3
package cn.timer.api.service.impl;

import cn.timer.api.config.sftp.SftpConfiguration;
4
import cn.timer.api.controller.disk.constant.FileAddressConstant;
5 6 7
import cn.timer.api.dto.disk.FileInfoDto;
import cn.timer.api.service.FtpService;
import cn.timer.api.utils.Md5;
8
import cn.timer.api.utils.aliyun.OSSUtil;
9 10 11 12
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
13
import org.springframework.beans.factory.annotation.Value;
14 15 16 17
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

18
import java.io.*;
19 20 21 22 23 24 25 26 27 28 29 30
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class FtpServiceImpl implements FtpService {

    @Autowired
    private SftpConfiguration config;
31 32
    @Autowired
    private OSSUtil oss;
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66


    @Override
    public boolean createDirs(String dirPath, ChannelSftp sftp) {
        if (dirPath != null && !dirPath.isEmpty() && sftp != null) {
            String[] dirs = Arrays.stream(dirPath.split("/")).filter(StringUtils::hasLength).toArray(String[]::new);

            for (String dir : dirs) {
                try {
                    sftp.cd(dir);
                    //log.info("stfp切换到目录:{}", dir);
                } catch (Exception e) {
                    try {
                        sftp.mkdir(dir);
                        //log.info("sftp创建目录:{}", dir);
                    } catch (SftpException e1) {
                        log.error("[sftp创建目录失败]:{}", dir, e1);
                        e1.printStackTrace();
                        throw new RuntimeException("sftp创建目录失败");
                    }
                    try {
                        sftp.cd(dir);
                        //log.info("stfp切换到目录:{}", dir);
                    } catch (SftpException e1) {
                        log.error("[sftp切换目录失败]:{}", dir, e1);
                        e1.printStackTrace();
                        throw new RuntimeException("sftp切换目录失败");
                    }
                }
            }
            return true;
        }
        return false;
    }
67

68
    @Override
69 70
    public List<FileInfoDto> uploadFile(MultipartFile[] files) {

71
        List<FileInfoDto> resultStrs = new ArrayList<FileInfoDto>();
72 73 74 75 76 77 78 79 80 81
        //存储地址判断
        if (FileAddressConstant.PHYSICS_OSS.equals(config.getFileAddress())) {
            ChannelSftp sftp = config.getSftpSocket();
            try {
                sftp.cd(config.getRoot());
                //log.info("sftp连接host", config.getRoot());
                boolean dirs = this.createDirs(config.getTargetPath(), sftp);
                if (!dirs) {
                    log.error("sftp创建目录失败", config.getTargetPath());
                    throw new RuntimeException("上传文件失败");
82
                }
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
                FileInfoDto dto = null;
                for (MultipartFile file : files) {
                    dto = new FileInfoDto();
                    String fileName = "";
                    String name = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
                    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                    if (config.isReservedName()) {
                        fileName = Md5.md5(name + UUID.randomUUID().toString()) + suffix;
                    } else {
                        fileName = UUID.randomUUID().toString() + suffix;
                    }
                    sftp.put(file.getInputStream(), fileName);
                    dto.setUrlPath(config.getServerUrl() + "/" + fileName);
                    dto.setResourceFileName(name);
                    dto.setFileName(fileName);
98

99 100 101 102 103 104
                    /*Float size = Float.parseFloat(String.valueOf(file.getSize())) / 1024;
                    BigDecimal b = new BigDecimal(size);
                    // 2表示2位 ROUND_HALF_UP表明四舍五入,
                    size = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();*/
                    dto.setFileSize(file.getSize());
                    dto.setFileSuffix(suffix);
105

106 107 108 109 110 111 112 113
                    resultStrs.add(dto);
                }
            } catch (Exception e) {
                log.error("上传文件失败", config.getTargetPath(), e);
                e.printStackTrace();
                throw new RuntimeException("上传文件失败");
            } finally {
                config.returnSftpSocket(sftp);
114
            }
115 116
        } else if (FileAddressConstant.ALIYUN_OSS.equals(config.getFileAddress())) {

117
        }
118
        return resultStrs;
119
    }
120 121 122 123 124 125 126 127 128


    /**
     * 下载单个文件
     *
     * @param remotePath:远程下载目录
     * @return
     */
    @Override
129
    public InputStream downloadFile(String remotePath) {
130
        ChannelSftp sftp = config.getSftpSocket();
131
        InputStream nputStream = null;
132 133 134
        try {
            // sftp.cd(remotePath);
            // mkdirs(localPath + localFileName);
135 136
            //sftp.get(remotePath, fieloutput);
            nputStream = sftp.get(remotePath);
137 138 139
            if (log.isInfoEnabled()) {
                log.info("===DownloadFile:" + remotePath + " success from sftp.");
            }
140
            return nputStream;
141
        } catch (SftpException e) {
142
            e.printStackTrace();
143
        } catch (Exception e) {
144
            e.printStackTrace();
145
        } finally {
146 147
            config.returnSftpSocket(sftp);
        }
148
        return nputStream;
149 150
    }

151
    @Override
152
    public boolean deleteFile(List<String> targetPath) {
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        ChannelSftp sftp = null;
        try {
            sftp = config.getSftpSocket();
            sftp.cd(config.getRoot());
            for (String path : targetPath) {
                sftp.rm(path);
            }
            return true;
        } catch (Exception e) {
            log.error("删除文件失败", targetPath, e);
            e.printStackTrace();
            throw new RuntimeException("删除文件失败");
        } finally {
            config.returnSftpSocket(sftp);
        }
    }
}