springboot上传下载文件--上传下载工具类(已封装)

简介: springboot工具类

 1、依赖

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
        <dependency>
      <groupId>com.jcraft</groupId>
      <artifactId>jsch</artifactId>
      <version>0.1.54</version>
    </dependency>

image.gif

2、配置(yml)

sftp:
  ip: 192.168.23.142
  port: 22
  username: root
  password: 123456
  downloadSleep: 100 #文件下载失败下次超时重试时间
  downloadRetry: 10 #文件下载失败重试次数
  uploadSleep: 100 #文件上传失败下次超时重试时间
  uploadRettry: 10  #文件上传失败重试次数

image.gif

3、SFTPUtils

package com.zj.docker.utils;
import com.jcraft.jsch.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.lang.reflect.Field;
import java.util.Properties;
/**
 * @Auther: zj
 * @Date: 2018/12/18 16:58
 * @Description:
 */
public class SFTPUtils {
    /**
     * 默认端口
     */
    private final static int DEFAULT_PORT = 22;
    private final static String HOST = "host";
    private final static String PORT = "port";
    private final static String USER_NAME = "userName";
    private final static String PASSWORD = "password";
    /**
     * 服务端保存的文件名
     */
    private String remote;
    /**
     * 服务端保存的路径
     */
    private String remotePath;
    /**
     * 本地文件
     */
    private File local;
    /**
     * 主机地址
     */
    private String host;
    /**
     * 端口
     */
    private int port = DEFAULT_PORT;
    /**
     * 登录名
     */
    private String userName;
    /**
     * 登录密码
     */
    private String password;
    private ChannelSftp sftp;
    public SFTPUtils(String host, int port, String userName, String password) {
        this.init(host, port, userName, password);
    }
    /**
     * 初始化
     *
     * @param host
     * @param port
     * @param userName
     * @param password
     * @date 2018/12/18
     */
    private void init(String host, int port, String userName, String password) {
        this.host = host;
        this.port = port;
        this.userName = userName;
        this.password = password;
    }
    /**
     * 连接sftp
     *
     * @throws JSchException
     * @date 2018/12/18
     */
    private void connect() throws JSchException, NoSuchFieldException, IllegalAccessException, SftpException {
        JSch jsch = new JSch();
        // 取得一个SFTP服务器的会话
        Session session = jsch.getSession(userName, host, port);
        // 设置连接服务器密码
        session.setPassword(password);
        Properties sessionConfig = new Properties();
        // StrictHostKeyChecking
        // "如果设为"yes",ssh将不会自动把计算机的密匙加入"$HOME/.ssh/known_hosts"文件,
        // 且一旦计算机的密匙发生了变化,就拒绝连接。
        sessionConfig.setProperty("StrictHostKeyChecking", "no");
        // 设置会话参数
        session.setConfig(sessionConfig);
        // 连接
        session.connect();
        // 打开一个sftp渠道
        Channel channel = session.openChannel("sftp");
        sftp = (ChannelSftp) channel;
        channel.connect();
        Class cl = ChannelSftp.class;
        Field f =cl.getDeclaredField("server_version");
        f.setAccessible(true);
        f.set(sftp, 2);
        sftp.setFilenameEncoding("GBK");
    }
    /**
     * 上传文件
     * @date 2018/12/18
     */
    public void uploadFile() throws Exception {
        FileInputStream inputStream = null;
        try {
            connect();
            if (isEmpty(remote)) {
                remote = local.getName();
            }
            if (!isEmpty(remotePath)) {
                sftp.cd(remotePath);
            }
            inputStream = new FileInputStream(local);
            sftp.put(inputStream, remote);
        } catch (Exception e) {
            throw e;
        } finally {
            sftp.disconnect();
            close(inputStream);
        }
    }
    public void uploadFile(InputStream inputStream) throws Exception {
        try {
            connect();
            if (isEmpty(remote)) {
                remote = local.getName();
            }
            if (!isEmpty(remotePath)) {
                createDir(remotePath);
            }
            sftp.put(inputStream, remote);
        } catch (Exception e) {
            throw e;
        } finally {
            sftp.disconnect();
            close(inputStream);
        }
    }
    @Async("taskExecutor")//异步
    public void uploadFile(String filename, String filePath, MultipartFile file) throws Exception {
        try {
            connect();
            if (!isEmpty( filePath )) {
                createDir( filePath );
            }
            sftp.put( file.getInputStream(), filename );
        }catch (Exception e) {
            throw e;
        } finally {
            sftp.disconnect();
            close(file.getInputStream());
        }
    }
    public boolean isDirExist(String directory) throws Exception {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }
    public void createDir(String createpath) throws Exception {
        try {
            if (isDirExist(createpath)) {
                this.sftp.cd(createpath);
            } else {
                String pathArry[] = createpath.split("/");
                for (String path : pathArry) {
                    if (path.equals("")) {
                        continue;
                    }
                    if (isDirExist(path.toString())) {
                        sftp.cd(path.toString());
                    } else {
                        // 建立目录
                        sftp.mkdir(path.toString());
                        // 进入并设置为当前目录
                        sftp.cd(path.toString());
                    }
                }
            }
        } catch (SftpException e) {
            throw new Exception("创建路径错误:" + createpath);
        }
    }
    /**
     * 下载
     * @date 2018/12/18
     */
    public void download() throws Exception {
        FileOutputStream output = null;
        try {
            this.connect();
            if (null != remotePath || !("".equals(remotePath))) {
                sftp.cd(remotePath);
            }
            output = new FileOutputStream(local);
            sftp.get(remote, output);
        } catch (Exception e) {
            throw e;
        } finally {
            sftp.disconnect();
            close(output);
        }
    }
    public void download(OutputStream outputStream) throws Exception {
        try {
            this.connect();
            if (null != remotePath || !("".equals(remotePath))) {
                sftp.cd(remotePath);
            }
            sftp.get(remote, outputStream);
        } catch (Exception e) {
            throw e;
        } finally {
            sftp.disconnect();
        }
    }
    public static boolean isEmpty(String str) {
        if (null == str || "".equals(str)) {
            return true;
        }
        return false;
    }
    public static void close(OutputStream... outputStreams) {
        for (OutputStream outputStream : outputStreams) {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void close(InputStream... inputStreams) {
        for (InputStream inputStream : inputStreams) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public void setRemote(String remote) {
        this.remote = remote;
    }
    public void setRemotePath(String remotePath) {
        this.remotePath = remotePath;
    }
    public void setLocal(File local) {
        this.local = local;
    }
}

image.gif

4、Controller

测试,这边就简单举了一个例子

@Value("${sftp.ip}")
    private String SFTP_ADDRESS; //ip
    @Value("${sftp.port}")
    private Integer SFTP_PORT; //port
    @Value("${sftp.username}")
    private String SFTP_USERNAME; //sftp username
    @Value("${sftp.password}")
    private String SFTP_PASSWORD; //sftp password
--------------------------------------------------
 /**
     * 上传文件到数据卷,普通用户权限
     * @param request
     * @param name 数据卷的名称
     * @param file 上传的文件
     * @return
     * @throws Exception
     */
    @PostMapping("/customer/uploadDocToVolume")
    public ResultVo customerUploadDocToVolume(HttpServletRequest request,
                                              @RequestParam("name") String name,
                                              @RequestParam("file") MultipartFile file
                                              ) throws Exception {
        //鉴权
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request, RoleEnum.User.getMessage() );
        if (Objects.equals( username, CommonEnum.FALSE.getMessage())) {
            return ResultVoUtil.error();
        }
        //校验参数
        if (StringUtils.isBlank( name )||file==null ) {
            return ResultVoUtil.error(CommonEnum.PARAM_ERROR.getMessage());
        }
        String bashPath ="/var/lib/docker/volumes/";
        String picSavePath = "/"+name+"/_data";
        SFTPUtils sftpUtils = new SFTPUtils( SFTP_ADDRESS,SFTP_PORT,SFTP_USERNAME,SFTP_PASSWORD);
        //上传文件,同步
        sftpUtils.uploadFile( file.getOriginalFilename(),bashPath+picSavePath,file );
        return ResultVoUtil.success("上传文件成功");
    }

image.gif


本篇文章到这里就结束啦,很感谢你能看到最后,欢迎关注!

相关文章
|
XML Java Maven
springboot-多环境配置文件
本文介绍了如何创建开发和生产环境的配置文件,并在IDEA和Maven中进行配置。开发环境中,通过设置profile为`dev`来指定配置文件;生产环境中,使用Maven命令参数`-Pprod`打包并指定配置文件。公共配置可放在`application.yml`中统一管理。日志配置需确保`logback-spring.xml`中的profile正确,以保证日志正常输出。
931 4
springboot-多环境配置文件
|
11月前
|
XML 前端开发 Java
SpringBoot实现文件上传下载功能
本文介绍了如何使用SpringBoot实现文件上传与下载功能,涵盖配置和代码实现。包括Maven依赖配置(如`spring-boot-starter-web`和`spring-boot-starter-thymeleaf`)、前端HTML页面设计、WebConfig路径映射配置、YAML文件路径设置,以及核心的文件上传(通过`MultipartFile`处理)和下载(利用`ResponseEntity`返回文件流)功能的Java代码实现。文章由Colorful_WP撰写,内容详实,适合开发者学习参考。
1024 0
|
存储 前端开发 Java
Springboot静态资源映射及文件映射
在Spring Boot项目中,为了解决前端访问后端存储的图片问题,起初尝试通过静态资源映射实现,但发现这种方式仅能访问打包时已存在的文件。对于动态上传的图片(如头像),需采用资源映射配置,将特定路径映射到服务器上的文件夹,确保新上传的图片能即时访问。例如,通过`addResourceHandler(&quot;/img/**&quot;).addResourceLocations(&quot;file:E:\\myProject\\forum_server\\&quot;)`配置,使前端可通过URL直接访问图片。
794 0
Springboot静态资源映射及文件映射
|
12月前
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——封装统一返回的数据结构
本文介绍了在Spring Boot中封装统一返回的数据结构的方法。通过定义一个泛型类`JsonResult&lt;T&gt;`,包含数据、状态码和提示信息三个属性,满足不同场景下的JSON返回需求。例如,无数据返回时可设置默认状态码&quot;0&quot;和消息&quot;操作成功!&quot;,有数据返回时也可自定义状态码和消息。同时,文章展示了如何在Controller中使用该结构,通过具体示例(如用户信息、列表和Map)说明其灵活性与便捷性。最后总结了Spring Boot中JSON数据返回的配置与实际项目中的应用技巧。
889 0
|
8月前
|
JSON Java 数据格式
Spring Boot返回Json数据及数据封装
在Spring Boot中,接口间及前后端的数据传输通常使用JSON格式。通过@RestController注解,可轻松实现Controller返回JSON数据。该注解是Spring Boot新增的组合注解,结合了@Controller和@ResponseBody的功能,默认将返回值转换为JSON格式。Spring Boot底层默认采用Jackson作为JSON解析框架,并通过spring-boot-starter-json依赖集成了相关库,包括jackson-databind、jackson-datatype-jdk8等常用模块,简化了开发者对依赖的手动管理。
743 3
|
12月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
Java 应用服务中间件
SpringBoot获取项目文件的绝对路径和相对路径
SpringBoot获取项目文件的绝对路径和相对路径
896 1
SpringBoot获取项目文件的绝对路径和相对路径
|
网络协议 Java
springboot配置hosts文件
springboot配置hosts文件
268 11
|
前端开发 Java easyexcel
SpringBoot操作Excel实现单文件上传、多文件上传、下载、读取内容等功能
SpringBoot操作Excel实现单文件上传、多文件上传、下载、读取内容等功能
1001 8
|
存储 前端开发 JavaScript

热门文章

最新文章