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

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

20
import java.io.*;
21 22 23 24 25 26 27 28 29 30 31 32
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;
33 34
    @Autowired
    private OSSUtil oss;
35 36
    @Autowired
    private OSSService ossService;
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 67 68 69 70


    @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;
    }
71

72
    @Override
73
    public List<FileInfoDto> uploadFile(int orgCode, MultipartFile[] files) {
74

75
        List<FileInfoDto> resultStrs = new ArrayList<FileInfoDto>();
76 77 78 79 80 81 82 83 84 85
        //存储地址判断
        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("上传文件失败");
86
                }
87 88 89 90 91 92 93 94 95 96 97 98 99 100
                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);
101
                    dto.setFileName(config.getRoot() + config.getTargetPath() + "/" +fileName);
102

103 104 105 106 107 108
                    /*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);
109

110 111 112 113 114 115 116 117
                    resultStrs.add(dto);
                }
            } catch (Exception e) {
                log.error("上传文件失败", config.getTargetPath(), e);
                e.printStackTrace();
                throw new RuntimeException("上传文件失败");
            } finally {
                config.returnSftpSocket(sftp);
118
            }
119
        } else if (FileAddressConstant.ALIYUN_OSS.equals(config.getFileAddress())) {
120
            resultStrs = ossService.uploadFile(orgCode, "disk",files);
121
        }
122
        return resultStrs;
123
    }
124 125 126 127 128


    /**
     * 下载单个文件
     *
129
     * @param diskFiles:远程下载目录
130 131 132
     * @return
     */
    @Override
133 134
    public InputStream downloadFile(DiskFiles diskFiles) {
        //存储地址判断
135
        InputStream nputStream = null;
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        if (diskFiles.getUrlPath().indexOf(config.getServerUrl())!=-1) {
            ChannelSftp sftp = config.getSftpSocket();
            try {
                // sftp.cd(remotePath);
                // mkdirs(localPath + localFileName);
                //sftp.get(remotePath, fieloutput);
                nputStream = sftp.get(diskFiles.getDiskPath());
                if (log.isInfoEnabled()) {
                    log.info("===DownloadFile:" + diskFiles.getDiskPath() + " success from sftp.");
                }
                return nputStream;
            } catch (SftpException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                config.returnSftpSocket(sftp);
153
            }
154 155
        }else if (FileAddressConstant.ALIYUN_OSS.equals(config.getFileAddress())) {
            nputStream = oss.downloadFileInputStream(diskFiles.getDiskPath());
156
        }
157
        return nputStream;
158 159
    }

160
    @Override
161
    public boolean deleteFile(List<String> targetPath) {
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        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);
        }
    }
}