| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package com.template.controller;
- import com.jcraft.jsch.*;
- import com.template.api.WelcomeFileControllerAPI;
- import com.template.model.result.CommonResult;
- import com.template.model.vo.UploadFileVo;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.multipart.MultipartFile;
- import java.io.InputStream;
- import java.util.Properties;
- /**
- * <p>
- * 前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2025-06-13
- */
- @RestController
- public class WelcomeFileController implements WelcomeFileControllerAPI {
- /**
- * 文件上传
- *
- * @param file 上传的文件
- * @return
- * @throws Exception
- */
- @Override
- public CommonResult uploadFile(MultipartFile file) throws Exception {
- UploadFileVo result = new UploadFileVo();
- String name = com.template.common.utils.StrUtils.getRandomName(file.getOriginalFilename());
- String user = "root"; //SFTP服务器用户名
- String password = "Waimai2024#"; // SFTP服务器密码
- String host = "172.16.40.126"; // SFTP服务器地址
- int port = 22; // SFTP 服务器端口
- String remoteDirPath = "/home/image"; // 远程目录路径
- //从MultipartFile对象中获取流
- InputStream inputStream = null;
- inputStream = file.getInputStream();
- //String downpath="/book/《Python爬虫开发与项目实战》.pdf";
- //String spath="C:/Users/F1339769/Desktop";
- JSch jsch = new JSch();
- Session session = null;
- ChannelSftp channelSftp = null;
- try {
- session = jsch.getSession(user, host, port);
- session.setPassword(password);
- Properties config = new Properties();
- config.put("StrictHostKeyChecking", "no");
- session.setConfig(config);
- session.connect(30000);
- System.out.println("连接成功");
- channelSftp = (ChannelSftp) session.openChannel("sftp");
- channelSftp.connect();
- // 创建远程目录
- String[] dirArr = remoteDirPath.split("/");
- String path = "";
- for (int i = 0; i < dirArr.length; i++) {
- path = path + "/" + dirArr[i];
- try {
- channelSftp.cd(path);
- } catch (SftpException e) {
- channelSftp.mkdir(path);
- channelSftp.cd(path);
- }
- }
- // 文件上传到远程服务器上
- channelSftp.put(inputStream, name);
- // 从远程服务器上下载文件
- //channelSftp.get(downpath, spath);
- result.setUrl("https://chtech.ncjti.edu.cn/welcome/homeimage/" + name);
- } catch (JSchException e) {
- e.printStackTrace();
- } finally {
- if (channelSftp != null) {
- channelSftp.disconnect();
- }
- if (session != null) {
- session.disconnect();
- }
- }
- if(!org.springframework.util.StringUtils.hasText(result.getUrl())){
- return CommonResult.fail("图片上传失败");
- }
- return CommonResult.ok(result);
- }
- }
|