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


前端与以前的是一致的.

相关文章
|
3天前
|
PHP Android开发
android通过http上传文件,服务器端用php写(原创)
android通过http上传文件,服务器端用php写(原创)
18 4
|
3天前
|
Java Linux
Springboot 解决linux服务器下获取不到项目Resources下资源
Springboot 解决linux服务器下获取不到项目Resources下资源
|
3天前
|
Java 容器
SpringBoot读取resources下的文件以及resources的资源路径
SpringBoot读取resources下的文件以及resources的资源路径
35 0
|
3天前
|
Java
SpringBoot文件上传单文件多文件上传
SpringBoot文件上传单文件多文件上传
14 0
|
3天前
|
Java 关系型数据库 MySQL
【MySQL × SpringBoot 突发奇想】全面实现流程 · xlsx文件,Excel表格导入数据库的接口(下)
【MySQL × SpringBoot 突发奇想】全面实现流程 · xlsx文件,Excel表格导入数据库的接口
12 0
|
3天前
|
Java 关系型数据库 MySQL
【MySQL × SpringBoot 突发奇想】全面实现流程 · xlsx文件,Excel表格导入数据库的接口(上)
【MySQL × SpringBoot 突发奇想】全面实现流程 · xlsx文件,Excel表格导入数据库的接口
18 0
|
3天前
|
前端开发 关系型数据库 MySQL
【MySQL × SpringBoot 突发奇想】全面实现流程 · 数据库导出Excel表格文件的接口
【MySQL × SpringBoot 突发奇想】全面实现流程 · 数据库导出Excel表格文件的接口
24 0
|
3天前
|
JavaScript Java API
【JavaEE】Spring Boot - 日志文件
【JavaEE】Spring Boot - 日志文件
6 0
|
3天前
|
安全 JavaScript Java
springboot实现文件防盗链设计
`shigen`,一位专注于Java、Python、Vue和Shell的博主,分享成长和技术。近期将探讨SpringBoot实现图片防盗链,通过限制`Referer`防止资源被盗用。基础版通过`WebMvcConfigurer`配置静态资源,升级版添加拦截器检查`Referer`,确保请求来源合法性。详细代码实现和案例可在文中链接找到。一起学习,每天进步!
46 13
springboot实现文件防盗链设计
|
3天前
|
Java 关系型数据库 MySQL
保姆级教程——将springboot项目部署到阿里云服务器包含环境配置(小白包会)
本文档详细介绍了将SpringBoot项目部署到阿里云服务器的步骤。首先,通过Xshell连接服务器,使用公网IP地址。接着,下载JDK的Linux版本,使用XFTP上传并解压,配置环境变量。然后,安装MySQL 5.7,包括下载YUM源、安装、启动服务以及修改root密码和开启远程访问。最后,将SpringBoot项目打包成jar,上传至服务器,使用`java -jar`命令运行,通过`nohup`确保服务持续运行。配置安全组以允许远程访问。

热门文章

最新文章