java上传文件到指定服务器

首先要知道服务器的用户名和密码。

注意:一般情况,如果不是强制要求,尽量不要将文件上传到服务器

步骤:

1.导入依赖

<!--图片上传到服务器需要的依赖-->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.54</version>
        </dependency>

2.编写配置文件application.yml

customize:
    remoteServer:
        sftp:
          SFTP_httpBaseUrl: /images/ # 访问附件的地址添加 一个映射 如  /images/ -》 /server-images/
          SFTP_httpPort: 80 # 公网访问的端口
          SFTP_directory: /server-images/ #主机保存附件目录
          SFTP_host: 192.168.1.10 #主机
          SFTP_port: 22 #端口号
          SFTP_username: root #用户名
          SFTP_password: 123456 #密码

 3.编写文件上传所需要的工具类

import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.util.Properties;
import java.util.UUID;


/**
 * 类描述:
 * 上传文件到服务器的 工具类
 *
 * @ClassName SFTPUtil
 * @Author msi
 * @Date 2020/9/2 23:29
 * @Version 1.0
 */
@Component
public class SFTPUtil {

    /**
     * 返回公网访问的地址前缀
     */
    @Value("${customize.remoteServer.sftp.SFTP_httpBaseUrl}")
    protected String baseUrl;
    /**
     * 公网访问的端口
     */
    @Value("${customize.remoteServer.sftp.SFTP_httpPort}")
    protected int port;
    /**
     * 主机保存的目录
     */
    @Value("${customize.remoteServer.sftp.SFTP_directory}")
    protected String directory;
    /**
     * 主机的IP
     */
    @Value("${customize.remoteServer.sftp.SFTP_host}")
    protected String host;
    /**
     * ssh端口
     */
    @Value("${customize.remoteServer.sftp.SFTP_port}")
    protected int sshPort;
    /**
     * 用户名
     */
    @Value("${customize.remoteServer.sftp.SFTP_username}")
    protected String username;
    /**
     * 密码
     */
    @Value("${customize.remoteServer.sftp.SFTP_password}")
    protected String password;

    /**
     * 上传多文件到指定远程主机
     * @param files     文件数组
     * @return list 
     */
    public List<String> uploadMultipartFilesToServer(MultipartFile[] files) throws SftpException, JSchException, IOException {
        List<String> list = new ArrayList<>();
        ChannelSftp sftp = null;
        Session session = null;
        sftp = this.connect(this.host, this.sshPort, this.username, this.password);
        session = sftp.getSession();
        for (int i = 0; i < files.length; i++) {
            String originalFilename = files[i].getOriginalFilename();
            // 生成文件夹名 yyyy-mm
            String relativePath = new StringBuilder().append(LocalDate.now().getYear())
                    .append("-").append(LocalDate.now().getMonthValue()).toString();

            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();

            int lastIndex = originalFilename.lastIndexOf(".");
            String fileSuffix = originalFilename.substring(lastIndex);
            String filePrefix = originalFilename.substring(0, lastIndex);
            String fileName = new StringBuilder().append(filePrefix).append(uuid).append(fileSuffix).toString();

            // 文件上层目录
            String directory = this.directory + relativePath;
            // 创建文件夹
            this.createDir(directory, sftp);
            // 进入文件夹内
            sftp.cd(directory);
            // 创建文件
            sftp.put(files[0].getInputStream(), fileName);
            // 拼接返回格式
            String s = new StringBuilder("http://").append(this.host).append(":").append(this.port)
                    .append(this.baseUrl).append(relativePath).append("/").append(fileName).toString();

            list.add(s);
        }
        // 关掉连接
        sftp.disconnect();
        sftp.getSession().disconnect();

        return list;
    }

    /**
     * 建立连接
     * @param host  主机
     * @param port  端口
     * @param username  用户名
     * @param password  密码
     * @return
     */
    public ChannelSftp connect(String host, int port, String username,
                               String password) {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            Session sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sftp;
    }

    /**
     * 创建目录
     *
     */
    public void createDir(String createpath, ChannelSftp sftp) {
        try {
            if (isDirExist(sftp, createpath)) {
                sftp.cd(createpath);
            }
            String pathArry[] = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            // 循环创建目录
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (isDirExist(sftp, filePath.toString())) {
                    sftp.cd(filePath.toString());
                } else {
                    // 建立目录
                    sftp.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    sftp.cd(filePath.toString());
                }
            }
            sftp.cd(createpath);
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }


    /**
     * 判断目录是否存在
     */
    public boolean isDirExist(ChannelSftp sftp, String directory) {
        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;
    }
}
 

4.编写对应controller进行调试

 @Autowired
    private UpdateFileUtil sftpUtil;
    /**
     * 上传文件到服务器
     *
     * @param files 图片
     * @return
     */
    @PostMapping("/file")
    public Result<List<String>> file(MultipartFile[] files) throws Exception {
        List<String> paths = sftpUtil.uploadMultipartFilesToServer(files);
        return Result.ofSuccess(paths);
    }

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将文件从Java上传到Linux服务器指定路径,可以使用SSH(Secure Shell)库和协议进行远程连接和文件传输。下面是一个简单的示例代码,展示了如何使用JSch库在Java中进行文件上传: ```java import com.jcraft.jsch.*; public class FileUploader { public static void main(String[] args) { String hostname = "服务器地址"; int port = 22; String username = "登录用户名"; String password = "登录密码"; String localFilePath = "本地文件路径"; String remoteDirectory = "远程服务器上的目标文件夹路径"; JSch jsch = new JSch(); try { Session session = jsch.getSession(username, hostname, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; sftpChannel.cd(remoteDirectory); // 切换到远程服务器上的目标文件夹路径 sftpChannel.put(localFilePath, ""); // 将本地文件上传到指定路径,指定空字符串表示保持原有文件名 sftpChannel.disconnect(); session.disconnect(); System.out.println("文件上传成功!"); } catch (JSchException | SftpException e) { e.printStackTrace(); } } } ``` 在上述代码中,你需要将代码中的服务器地址、登录用户名、登录密码、本地文件路径以及远程服务器上的目标文件夹路径替换为你自己的实际设置。 这个例子使用JSch库建立与远程服务器的SSH连接,并使用SFTP协议进行文件传输。首先,通过创建一个Session对象,设置登录用户名、服务器地址和端口号,并使用密码进行身份验证。然后,打开一个sftp通道,连接到远程服务器。通过调用cd()方法切换到目标文件夹路径。最后,使用put()方法将本地文件上传到指定的远程路径。完成后,断开sftp通道和SSH会话。 希望这个示例能对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值