【文件上传】Java进行跨服务器文件/图片上传

一、引入相关依赖

<!--        进行linux服务器之间的文件传输-->
        <dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>pinyin4j</artifactId>
            <version>2.5.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.8.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>
        </dependency>
        <!--        FTP文件上传至linux服务器-->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.49</version>
        </dependency>

二、添加工具类

@Component
public class FTPUtil {


    private static String host;
    @Value(value = "${ftp-centos.host}")
    public  void setHost(String hostName){
        host = hostName;
    }

    private static Integer port;
    @Value(value = "${ftp-centos.port}")
    public  void setPort(Integer portName) {
        port = portName;
    }

    private static String user;
    @Value(value = "${ftp-centos.user}")
    public  void setUser(String userName) {
      user = userName;
    }

    private static String password;
    @Value(value = "${ftp-centos.password}")
    public  void setPassword(String passwordName) {
        password = passwordName;
    }



    private static String basePath;
    @Value(value = "${ftp-centos.basePath}")
    public  void setBasePath(String basePath) {
        FTPUtil.basePath = basePath;
    }

    public static void sshSftp(byte[] bytes, String fileName) throws Exception {
        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();
        if (port<= 0) {
            //连接服务器,采用默认端口
            session = jsch.getSession(user, host);
        } else {
            //采用指定的端口连接服务器
            session = jsch.getSession(user, host, port);
        }

        //如果服务器连接不上,则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }
        //设置登陆主机的密码
        session.setPassword(password);
        //设置第一次登陆的时候提示,可选值:(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);
        OutputStream outstream = null;
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //进入服务器指定的文件夹
            sftp.cd(basePath);
            //列出服务器指定的文件列表
//            Vector v = sftp.ls("*");
//            for(int i=0;i<v.size();i++){
//                System.out.println(v.get(i));
//            }
            //以下代码实现从本地上传一个文件到服务器,如果要实现下载,对换以下流就可以了
            outstream = sftp.put(fileName);
            outstream.write(bytes);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流操作
            if (outstream != null) {
                outstream.flush();
                outstream.close();
            }
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
    }
}

三、进行YML配置

#上传文件到文件服务器的配置
ftp-centos:
  #IP
  host: IP地址
  #端口
  port: 22
  user: 用户名
  password: 密码
  basePath: 文件存放的文件夹地址

四、业务代码演示

    @PostMapping("uploadImg")
    public void upload(MultipartFile file){
        try {
            //文件名称
            String imgName = System.currentTimeMillis() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            byte[] bytes = file.getBytes();//获取文件的字节数组
            FTPUtil.sshSftp(bytes, imgName);//进行文件传输
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用HTTP协议进行服务器文件上传和下载。以下是一个简单的示例代码: 文件上传: ```java public void uploadFile(String urlStr, String filePath) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + "---------------------------7d4a6d158c9"); OutputStream out = conn.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(filePath); byte[] buffer = new byte[8192]; int bytesRead = 0; while ((bytesRead = fileInputStream.read(buffer, 0, 8192)) != -1) { out.write(buffer, 0, bytesRead); } out.close(); fileInputStream.close(); conn.getResponseCode(); } ``` 文件下载: ```java public void downloadFile(String urlStr, String filePath) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); InputStream in = conn.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream(filePath); byte[] buffer = new byte[8192]; int bytesRead = 0; while ((bytesRead = in.read(buffer, 0, 8192)) != -1) { fileOutputStream.write(buffer, 0, bytesRead); } fileOutputStream.close(); in.close(); conn.disconnect(); } ``` 需要注意的是,上传和下载的URL需要指向正确的服务器地址和文件路径。另外,上传需要设置正确的Content-Type和boundary。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值