SpringBoot上传文件到远程服务器(二十九)中

二.三 通过不同的环境,选择不同的实现

@Configuration
public class JavaConfig {
    @Autowired(required = false)
    private Sftp sftp;
    @Autowired(required = false)
    private FtpUtil ftpUtil;
    /**
     条件符合时,创建
     */
    @Bean("fileService")
    @Profile("ftp")
    FileService ftp(){
        return new FtpFileServiceImpl(ftpUtil);
    }
    /**
     条件符合时,创建
     */
    @Bean("fileService")
    @Profile("sftp")
    FileService cat(){
        return new SftpFileServiceImpl(sftp);
    }
}


二.四 不同的实现

二.四.一 FTP 实现

FtpFileServiceImpl.java

@Log4j2
public class FtpFileServiceImpl implements FileService {
    private FtpUtil ftpUtil;
    public FtpFileServiceImpl(FtpUtil ftpUtil){
        this.ftpUtil=ftpUtil;
    }
    @Override
    public String upload(String dest,String fileName, File file) {
        if(StringUtils.isEmpty(fileName)){
            fileName=file.getName();
        }
        FTPClient ftpClient=null;
        //切换到相应的目录
       try{
           ftpClient=ftpUtil.createFileClient();
           boolean isExistDir = ftpClient.changeWorkingDirectory(dest);
           if(!isExistDir){
               ftpClient.makeDirectory(dest);
               ftpClient.changeWorkingDirectory(dest);
           }
           //保存文件
           ftpClient.storeFile(fileName,new FileInputStream(file));
           log.info("上传文件成功");
           return dest+fileName;
       }catch (Exception e){
           log.error("上传文件失败,{}",e);
       }finally{
           ftpUtil.close(ftpClient);
       }
       return null;
    }
    @Override
    public String pathUpload(String path, File file) {
        //切换到相应的目录
        String[] split = path.split(File.separator);
        int size=split.length;
        FTPClient ftpClient=null;
        try{
            ftpClient=ftpUtil.createFileClient();
            for (int i=0;i<size-2;i++) {
                String tempPath=split[i];
                if (StringUtils.isEmpty(tempPath)) {
                    continue;
                }
                if (!ftpClient.changeWorkingDirectory(tempPath)) {
                    ftpClient.makeDirectory(tempPath);
                    ftpClient.changeWorkingDirectory(tempPath);
                }
            }
            //保存文件
            ftpClient.storeFile(split[size-1],new FileInputStream(file));
            log.info("上传文件成功");
            return path;
        }catch (Exception e){
            log.error("上传文件失败,{}",e);
        }finally {
            ftpUtil.close(ftpClient);
        }
        return null;
    }
    @Override
    public void download(String dest,String fileName, File outFile) {
        pathDownload(dest+fileName,outFile);
    }
    @Override
    public void pathDownload(String path, File outFile) {
        FTPClient ftpClient=null;
        try {
            ftpClient=ftpUtil.createFileClient();
            ftpClient.retrieveFile(path,new FileOutputStream(outFile));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            ftpUtil.close(ftpClient);
        }
    }
}


二.四.二 SFTP 实现

@Log4j2
public class SftpFileServiceImpl implements FileService {
    private Sftp sftp;
    public SftpFileServiceImpl(Sftp sftp){
        this.sftp=sftp;
    }
    @Override
    public String upload(String dest,String fileName, File file) {
        if(StringUtils.isEmpty(fileName)){
            fileName=file.getName();
        }
        try {
            sftp.cd(dest);
        } catch (Exception e) {
            log.info("该文件夹不存在,自动创建");
            sftp.mkdir(dest);
        }
        try{
            sftp.getClient().put(
                    new FileInputStream(file),
                    dest+fileName
            );
            log.info(">>>文件上传成功");
            return dest+fileName;
        }catch (Exception e){
            log.error("文件上传失败,{}",e);
            return null;
        }
    }
    @Override
    public String pathUpload(String path, File file) {
        try{
            sftp.getClient().put(new FileInputStream(file),path);
        }catch (Exception e){
            log.error("文件上传失败,{}",e);
            return null;
        }
        return null;
    }
    @Override
    public void download(String dest,String fileName, File outFile) {
        sftp.download(dest+fileName,outFile);
    }
    @Override
    public void pathDownload(String path, File outFile) {
        sftp.download(path,outFile);
    }
}


二.五 controller 控制器

@Controller
public class FileController {
    @Autowired
    private FileService fileService;
    @Autowired
    private SshFileProperties sshFileProperties;
    @RequestMapping("/")
    public String index(){
        return "index";
    }
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        // 获得 classpath 的绝对路径
        String realPath = ResourceUtils.getURL("classpath:").getPath()+"static/files";
        File newFile = new File(realPath);
        // 如果文件夹不存在、则新建
        if (!newFile.exists()){
            newFile.mkdirs();
        }
        // 上传
        File uploadFile=new File(newFile, file.getOriginalFilename());
        file.transferTo(uploadFile);
        String uploadPath = fileService.upload(sshFileProperties.getUploadFilePath(),file.getOriginalFilename(), uploadFile);
        //将以前的文件删除掉
        uploadFile.delete();
        return "上传文件成功,地址为:"+uploadPath;
    }
    @GetMapping("download")
    @ResponseBody
    public String download(String fileName) throws IOException {
        // 获得待下载文件所在文件夹的绝对路径
        String realPath =sshFileProperties.getUploadFilePath();
        //构建新的文件
        File downloadDirFile=new File(sshFileProperties.getDownloadFilePath());
        // 如果文件夹不存在、则新建
        if (!downloadDirFile.exists()){
            downloadDirFile.mkdirs();
        }
        // 上传
        File downloadFile=new File(downloadDirFile,fileName);
        String downloadPath=sshFileProperties.getDownloadFilePath()+fileName;
        fileService.download(realPath,fileName,downloadFile);
        return "文件下载成功,下载后的目录为:"+downloadPath;
    }
}


前端与以前的是一致的.

上一篇:JettyServer无web.xml


下一篇:体验有奖 | 1 分钟 Serverless 部署掌上游戏机,“一行命令”找回小时候的乐趣!