首先要知道服務(wù)器的用戶名和密碼。
注意:一般情況,如果不是強(qiáng)制要求,盡量不要將文件上傳到服務(wù)器
步驟:
1.導(dǎo)入依賴
<!--圖片上傳到服務(wù)器需要的依賴-->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>com.jcraft</groupId>
? ? ? ? ? ? <artifactId>jsch</artifactId>
? ? ? ? ? ? <version>0.1.54</version>
? ? ? ? </dependency>
2.編寫(xiě)配置文件application.yml
customize:
?? ?remoteServer:
?? ? ? ?sftp:
?? ? ? ? ?SFTP_httpBaseUrl: /images/ # 訪問(wèn)附件的地址添加 一個(gè)映射 如 ?/images/ -》 /server-images/
?? ? ? ? ?SFTP_httpPort: 80 # 公網(wǎng)訪問(wèn)的端口
?? ? ? ? ?SFTP_directory: /server-images/ #主機(jī)保存附件目錄
?? ? ? ? ?SFTP_host: 192.168.1.10 #主機(jī)
?? ? ? ? ?SFTP_port: 22 #端口號(hào)
?? ? ? ? ?SFTP_username: root #用戶名
?? ? ? ? ?SFTP_password: 123456 #密碼
?3.編寫(xiě)文件上傳所需要的工具類
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;
/**
?* 類描述:
?* 上傳文件到服務(wù)器的 工具類
?*
?* @ClassName SFTPUtil
?* @Author msi
?* @Date 2020/9/2 23:29
?* @Version 1.0
?*/
@Component
public class SFTPUtil {? ? /**
? ? ?* 返回公網(wǎng)訪問(wèn)的地址前綴
? ? ?*/
? ? @Value("${customize.remoteServer.sftp.SFTP_httpBaseUrl}")
? ? protected String baseUrl;
? ? /**
? ? ?* 公網(wǎng)訪問(wèn)的端口
? ? ?*/
? ? @Value("${customize.remoteServer.sftp.SFTP_httpPort}")
? ? protected int port;
? ? /**
? ? ?* 主機(jī)保存的目錄
? ? ?*/
? ? @Value("${customize.remoteServer.sftp.SFTP_directory}")
? ? protected String directory;
? ? /**
? ? ?* 主機(jī)的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;? ? /**
? ? ?* 上傳多文件到指定遠(yuǎn)程主機(jī)
? ? ?* @param files ? ? 文件數(shù)組
? ? ?* @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;
? ? ? ? ? ? // 創(chuàng)建文件夾
? ? ? ? ? ? this.createDir(directory, sftp);
? ? ? ? ? ? // 進(jìn)入文件夾內(nèi)
? ? ? ? ? ? sftp.cd(directory);
? ? ? ? ? ? // 創(chuàng)建文件
? ? ? ? ? ? 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);
? ? ? ? }
? ? ? ? // 關(guān)掉連接
? ? ? ? sftp.disconnect();
? ? ? ? sftp.getSession().disconnect();? ? ? ? return list;
? ? }? ? /**
? ? ?* 建立連接
? ? ?* @param host ?主機(jī)
? ? ?* @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;
? ? }? ? /**
? ? ?* 創(chuàng)建目錄
? ? ?*
? ? ?*/
? ? public void createDir(String createpath, ChannelSftp sftp) {
? ? ? ? try {
? ? ? ? ? ? if (isDirExist(sftp, createpath)) {
? ? ? ? ? ? ? ? sftp.cd(createpath);
? ? ? ? ? ? }
? ? ? ? ? ? String pathArry[] = createpath.split("/");
? ? ? ? ? ? StringBuffer filePath = new StringBuffer("/");
? ? ? ? ? ? // 循環(huán)創(chuàng)建目錄
? ? ? ? ? ? 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());
? ? ? ? ? ? ? ? ? ? // 進(jìn)入并設(shè)置為當(dāng)前目錄
? ? ? ? ? ? ? ? ? ? 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.編寫(xiě)對(duì)應(yīng)controller進(jìn)行調(diào)試文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-812098.html
?@Autowired
? ? private UpdateFileUtil sftpUtil;
? ? /**
? ? ?* 上傳文件到服務(wù)器
? ? ?*
? ? ?* @param files 圖片
? ? ?* @return
? ? ?*/
? ? @PostMapping("/file")
? ? public Result<List<String>> file(MultipartFile[] files) throws Exception {
? ? ? ? List<String> paths = sftpUtil.uploadMultipartFilesToServer(files);
? ? ? ? return Result.ofSuccess(paths);
? ? }文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-812098.html
到了這里,關(guān)于java上傳文件到指定服務(wù)器的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!