JAVA代碼實現上傳文件至文件服務器(遠程服務器、非項目當前所在服務器)


步驟一:添加依賴

<!--sftp文件上傳-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

步驟二:編寫工具類

package com.example.vue.vuedemo;


import com.jcraft.jsch.Channel;
import com.jcraft.jsch.*;

import java.io.*;

/**
* Created by jlm on 2019-09-17 17:44
*/
public class FtpUtils {

/**
* 利用JSch包實現SFTP上傳文件
* @param bytes 文件字節流
* @param fileName 文件名
* @throws Exception
*/
public static void sshSftp(byte[] bytes,String fileName) throws Exception{
//指定的服務器地址
String ip = "服務器ip地址";
//用戶名
String user = "用戶名";
//密碼
String password = "密碼";
//服務器端口 默認22
int port = 22;
//上傳文件到指定服務器的指定目錄 自行修改
String path = "/root";

Session session = null;
Channel channel = null;


JSch jsch = new JSch();


if(port <=0){
//連接服務器,采用默認端口
session = jsch.getSession(user, ip);
}else{
//采用指定的端口連接服務器
session = jsch.getSession(user, ip ,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(path);

//列出服務器指定的文件列表
// 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();
}
}
}

}

步驟三:寫一個接口上傳文件,調用工具類方法即可

package com.example.vue.vuedemo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
* Created by jlm on 2019-09-17 17:42
*/
@RestController
public class UploadController {


@RequestMapping("file")
public void upload(HttpServletRequest httpServletRequest, MultipartFile file) throws Exception {
byte[] bytes = file.getBytes();
FtpUtils.sshSftp(bytes,"1111.jpg");

}

}


————————————————
版權聲明:本文為CSDN博主「Rice_kil」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/Rice_kil/article/details/100934710


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM