java web 实现Sftp文件上传下载

本文档详细介绍了使用Java Web实现SFTP文件上传和下载的步骤,包括连接FTP服务器、上传文件、下载文件及图片展示。通过JSch库进行操作,提供关键代码示例,帮助开发者实现SFTP功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路

1.首先连接ftp服务器

2.连接到服务器之后如何上传文件

3.上传后如何获取文件

4.文件格式是图片如何展示到客户端浏览器

5.服务端代码如何接收客户端的文件以及如何返回响应信息给浏览器

 主要jar包依赖文件

<dependency>
      <groupId>com.jcraft</groupId>
      <artifactId>jsch</artifactId>
      <version>0.1.54</version>
 </dependency>
        <!-- jsch 所依赖的jar包  -->
<dependency>
      <groupId>com.jcraft</groupId>
      <artifactId>jzlib</artifactId>
      <version>1.1.1</version>
  </dependency>

public class SftpUtils {

   private static final Logger log = LoggerFactory.getLogger(SftpUtils.class);
   private static ChannelSftp sftp;
   public static Properties properties = LoadProperties.getProperties("/config/sftp.properties");
   private static Channel channel;
   private static Session sshSession;

    /**
     * 登陆SFTP服务器
     * @return
     */
    public static boolean getConnect() throws Exception{
        log.info("进入SFTP====");
        boolean result = false;
        JSch jsch = new JSch();
        //获取sshSession  账号-ip-端口,从properties文件中获取连接ftp服务器的相关信息
        sshSession  =jsch.getSession(properties.getProperty("user"), properties.getProperty("ip"), Integer.parseInt(properties.getProperty("port")));
        //添加密码
        sshSession.setPassword(properties.getProperty("password"));
        Properties sshConfig = new Properties();
        //严格主机密钥检查
        sshConfig.put("StrictHostKeyChecking", "no");

        sshSession.setConfig(sshConfig);
        //开启sshSession链接
        sshSession.connect();
        //获取sftp通道
        channel = sshSession.openChannel("sftp");
        //开启
        channel.connect();
        sftp = (ChannelSftp) channel;
        result = true;
        return result;
    }
    
    /**
             * 文件上传
     * @param inputStream 上传的文件输入流
     * @param fileCategory 存储文件目录分类
     * @return
     */
    public static String upload(InputStream inputStream, String fileCategory, String fileName) throws Exception{
        String destinationPath = properties.getProperty("destinationPath")+fileCategory;
        try {
            sftp.cd(destinationPath);
            //获取随机文件名
            fileName  = UUID.randomUUID().toString().replace("-", "") + fileName;
            //文件名是 随机数加文件名的后5位
            sftp.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值