FtpServiceImpl.java 5.64 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package cn.timer.api.service.impl;

import cn.timer.api.config.sftp.SftpConfiguration;
import cn.timer.api.dto.disk.FileInfoDto;
import cn.timer.api.service.FtpService;
import cn.timer.api.utils.Md5;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

15
import java.io.*;
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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
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;


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

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    @Override
    public List<FileInfoDto> uploadFile(String targetPath, MultipartFile[] files, boolean reservedName) {
        ChannelSftp sftp = config.getSftpSocket();
        List<FileInfoDto> resultStrs = new ArrayList<FileInfoDto>();
        try {
            sftp.cd(config.getRoot());
            //log.info("sftp连接host", config.getRoot());
            boolean dirs = this.createDirs(targetPath, sftp);
            if (!dirs) {
                log.error("sftp创建目录失败", targetPath);
                throw new RuntimeException("上传文件失败");
            }
            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 (reservedName) {
82
                    fileName = Md5.md5(name + UUID.randomUUID().toString()) + suffix;
83
                } else {
84
                    fileName = UUID.randomUUID().toString() + suffix;
85 86
                }
                sftp.put(file.getInputStream(), fileName);
87
                dto.setUrlPath(config.getServerUrl() + "/" + fileName);
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
                dto.setResourceFileName(name);
                dto.setFileName(fileName);

                /*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);

                resultStrs.add(dto);
            }
            return resultStrs;
        } catch (Exception e) {
            log.error("上传文件失败", targetPath, e);
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        } finally {
            config.returnSftpSocket(sftp);
        }
    }
109 110 111 112 113 114 115 116 117 118



    /**
     * 下载单个文件
     *
     * @param remotePath:远程下载目录
     * @return
     */
    @Override
119
    public InputStream downloadFile(String remotePath) {
120
        ChannelSftp sftp = config.getSftpSocket();
121
        InputStream nputStream = null;
122 123 124
        try {
            // sftp.cd(remotePath);
            // mkdirs(localPath + localFileName);
125 126
            //sftp.get(remotePath, fieloutput);
            nputStream = sftp.get(remotePath);
127 128 129
            if (log.isInfoEnabled()) {
                log.info("===DownloadFile:" + remotePath + " success from sftp.");
            }
130 131
            return nputStream;
        } catch ( SftpException e) {
132
            e.printStackTrace();
133
        } catch (Exception e){
134
            e.printStackTrace();
135
        }finally {
136 137
            config.returnSftpSocket(sftp);
        }
138
        return nputStream;
139 140
    }

141
    @Override
142
    public boolean deleteFile(List<String> targetPath) {
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        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);
        }
    }
}