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


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

相关文章
|
21天前
|
存储 前端开发 Java
SpringBoot使用云端资源url下载文件的接口写法
在Spring Boot中实现从云端资源URL下载文件的功能可通过定义REST接口完成。示例代码展示了一个`FileDownloadController`,它包含使用`@GetMapping`注解的方法`downloadFile`,此方法接收URL参数,利用`RestTemplate`下载文件,并将文件字节数组封装为`ByteArrayResource`返回给客户端。此外,通过设置HTTP响应头,确保文件以附件形式下载。这种方法适用于从AWS S3或Google Cloud Storage等云服务下载文件。
124 7
|
4天前
|
JavaScript 前端开发 easyexcel
基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的前后端完整过程
本文展示了基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的完整过程,包括后端使用EasyExcel生成Excel文件流,前端通过Blob对象接收并触发下载的操作步骤和代码示例。
25 0
基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的前后端完整过程
|
19天前
|
JSON 前端开发 Java
SpringBoot3怎么做统一结果封装?
在Spring Boot应用中,统一结果封装有助于团队协作,确保一致的API响应格式,提升代码质量和维护性。主要优点包括:简化前端集成工作,减少后端重复编码,以及增强接口的可维护性。实现上,首先定义`Result`类来封装响应状态码、消息、数据及时间戳;其次,通过`ResultCode`枚举类标准化状态信息。示例代码展示了如何构建这些类,并通过一个简单的控制器方法演示了如何使用它们返回JSON格式的响应结果。
|
1天前
|
存储 Java API
SpringBoot + MinIO 实现文件切片极速上传技术
【8月更文挑战第19天】在现代互联网应用中,文件上传是一个常见且重要的功能。然而,随着文件体积的增大,传统的文件上传方式往往面临效率低下、耗时过长等问题。为了提升大文件上传的速度和效率,我们可以采用文件切片上传技术,并结合SpringBoot和MinIO来实现这一功能。
8 0
|
6天前
|
Java
Java SpringBoot FTP 上传下载文件
Java SpringBoot FTP 上传下载文件
10 0
|
6天前
|
JavaScript Java
SpringBoot 下载文件
SpringBoot 下载文件
13 0
|
6天前
|
JavaScript Java Spring
SpringBoot 接口输出文件流 & Vue 下载文件流,获取 Header 中的文件名
SpringBoot 接口输出文件流 & Vue 下载文件流,获取 Header 中的文件名
22 0
|
19天前
|
存储 运维 Java
SpringBoot使用log4j2将日志记录到文件及自定义数据库
通过上述步骤,你可以在Spring Boot应用中利用Log4j2将日志输出到文件和数据库中。这不仅促进了良好的日志管理实践,也为应用的监控和故障排查提供了强大的工具。强调一点,配置文件和代码的具体实现可能需要根据应用的实际需求和运行环境进行调优和修改,始终记住测试配置以确保一切运行正常。
102 0
|
20天前
|
XML Java API
springboot基础及上传组件封装
springboot基础及上传组件封装
12 0
|
21天前
|
前端开发 Java 网络架构
SpringBoot使用接口下载图片的写法
在Spring Boot中实现图片下载功能涉及定义一个REST接口来发送图片文件。首先,创建`ImageController`类,并在其中定义`downloadImage`方法,该方法使用`@GetMapping`注解来处理HTTP GET请求。方法内部,通过`Files.readAllBytes`读取图片文件到字节数组,再将该数组封装成`ByteArrayResource`。接着,设置`HttpHeaders`以指定文件名为`image.jpg`并配置为附件下载。