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

简介: 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;
    }
}


前端与以前的是一致的.

相关文章
|
8月前
|
XML Java Maven
springboot-多环境配置文件
本文介绍了如何创建开发和生产环境的配置文件,并在IDEA和Maven中进行配置。开发环境中,通过设置profile为`dev`来指定配置文件;生产环境中,使用Maven命令参数`-Pprod`打包并指定配置文件。公共配置可放在`application.yml`中统一管理。日志配置需确保`logback-spring.xml`中的profile正确,以保证日志正常输出。
481 4
springboot-多环境配置文件
|
9月前
|
存储 前端开发 Java
Springboot静态资源映射及文件映射
在Spring Boot项目中,为了解决前端访问后端存储的图片问题,起初尝试通过静态资源映射实现,但发现这种方式仅能访问打包时已存在的文件。对于动态上传的图片(如头像),需采用资源映射配置,将特定路径映射到服务器上的文件夹,确保新上传的图片能即时访问。例如,通过`addResourceHandler(&quot;/img/**&quot;).addResourceLocations(&quot;file:E:\\myProject\\forum_server\\&quot;)`配置,使前端可通过URL直接访问图片。
541 0
Springboot静态资源映射及文件映射
|
8月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
10月前
|
XML Java 应用服务中间件
Spring Boot 两种部署到服务器的方式
本文介绍了Spring Boot项目的两种部署方式:jar包和war包。Jar包方式使用内置Tomcat,只需配置JDK 1.8及以上环境,通过`nohup java -jar`命令后台运行,并开放服务器端口即可访问。War包则需将项目打包后放入外部Tomcat的webapps目录,修改启动类继承`SpringBootServletInitializer`并调整pom.xml中的打包类型为war,最后启动Tomcat访问应用。两者各有优劣,jar包更简单便捷,而war包适合传统部署场景。需要注意的是,war包部署时,内置Tomcat的端口配置不会生效。
2492 17
Spring Boot 两种部署到服务器的方式
|
Java 应用服务中间件
SpringBoot获取项目文件的绝对路径和相对路径
SpringBoot获取项目文件的绝对路径和相对路径
665 1
SpringBoot获取项目文件的绝对路径和相对路径
|
XML Java Kotlin
springboot + minio + kkfile实现文件预览
本文介绍了如何在容器中安装和启动kkfileviewer,并通过Spring Boot集成MinIO实现文件上传与预览功能。首先,通过下载kkfileviewer源码并构建Docker镜像来部署文件预览服务。接着,在Spring Boot项目中添加MinIO依赖,配置MinIO客户端,并实现文件上传与获取预览链接的接口。最后,通过测试验证文件上传和预览功能的正确性。
1206 4
springboot + minio + kkfile实现文件预览
|
12月前
|
监控 IDE Java
如何在无需重新启动服务器的情况下在 Spring Boot 上重新加载我的更改?
如何在无需重新启动服务器的情况下在 Spring Boot 上重新加载我的更改?
1107 8
|
网络协议 Java
springboot配置hosts文件
springboot配置hosts文件
195 11
|
存储 前端开发 JavaScript