日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Springboot通过SFTP上传文件到服务器

發(fā)布時間:2023/12/31 javascript 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Springboot通过SFTP上传文件到服务器 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

流程是這樣的:

前端選擇文件上傳-------->調(diào)用后臺接口,后臺連接服務(wù)器(Linux)--------->上傳成功

?前端無論是通過ajax,還是form表單直接提交都可以,這里暫時以form方式提交 這里需要依靠一個Sftps的工具類


先導(dǎo)入依賴

<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version> </dependency>

Sftps.java:

public final class Sftps {private static final Logger log = LoggerFactory.getLogger(Sftps.class);private Session sshSession;private ChannelSftp sftp;/*** 連接sftp服務(wù)器* @param host* @param port* @param username* @param password* @return* @throws Exception*/public ChannelSftp connect(String host, int port, String username, String password) throws Exception {JSch jsch = new JSch();sshSession = jsch.getSession(username, host, port);log.debug("Session created.");sshSession.setPassword(password);Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);sshSession.connect();log.debug("Session connected.");log.debug("Opening Channel.");Channel channel = sshSession.openChannel("sftp");channel.connect();sftp = (ChannelSftp) channel;log.debug("Connected to " + host + ".");return sftp;}/*** 連接sftp服務(wù)器* @param host* @param port* @param username* @param privateKey* @param passphrase* @return* @throws Exception*/public ChannelSftp connect(String host, int port, String username, String privateKey ,String passphrase) throws Exception {JSch jsch = new JSch();//設(shè)置密鑰和密碼if (!StringUtils.isEmpty(privateKey)) {if (!StringUtils.isEmpty(passphrase)) {//設(shè)置帶口令的密鑰jsch.addIdentity(privateKey, passphrase);} else {//設(shè)置不帶口令的密鑰jsch.addIdentity(privateKey);}}sshSession = jsch.getSession(username, host, port);log.debug("Session created.");Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);sshSession.connect();log.debug("Session connected.");log.debug("Opening Channel.");Channel channel = sshSession.openChannel("sftp");channel.connect();sftp = (ChannelSftp) channel;log.debug("Connected to " + host + ".");return sftp;}public void portForwardingL(int lport, String rhost, int rport) throws Exception {int assinged_port = sshSession.setPortForwardingL(lport, rhost, rport);System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);}/*** 斷開連接*/public void disconnect() {if (sftp != null) sftp.disconnect();if (sshSession != null) sshSession.disconnect();}/*** 上傳文件** @param directory* 上傳的目錄* @param uploadFile* 要上傳的文件* @param sftp*/public void upload(String directory, String uploadFile) throws Exception {sftp.cd(directory);File file = new File(uploadFile);sftp.put(new FileInputStream(file), file.getName());}public void upload(String directory, File file) throws Exception {sftp.cd(directory);sftp.put(new FileInputStream(file), file.getName());System.out.println("upload file "+file.getAbsolutePath() + " to host " + sshSession.getHost());}//利用流上傳文件 fileNamepublic void uploadfileInputStream(MultipartFile file, String directory, String fileName) throws Exception {sftp.cd(directory);sftp.put(file.getInputStream(),fileName);}public void uploadDir(File src, String dst) throws Exception{if (!exist(dst)) {sftp.mkdir(dst);}if (src.isFile()) {upload(dst, src);} else {for (File file : src.listFiles()) {if (file.isDirectory()) {uploadDir(file, dst + "/" + file.getName());}upload(dst, file);}}}/*** 目錄是否查找* @param path* @return* @throws SftpException*/public boolean exist(String path) throws SftpException {String pwd = sftp.pwd();try {sftp.cd(path);} catch (SftpException e) {if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {return false;} else {throw e;}} finally {sftp.cd(pwd);}return true;}/*** 下載文件* @param directory* @param downloadFile* @param saveFile* @throws Exception*/public void download(String directory, String downloadFile, String saveFile) throws Exception {sftp.cd(directory);File file = new File(saveFile);sftp.get(downloadFile, new FileOutputStream(file));}/*** 下載文件* @param directory* @param downloadFile* @param saveFile* @throws Exception*/public void download(String directory, String downloadFile, File saveFile) throws Exception {sftp.cd(directory);sftp.get(downloadFile, new FileOutputStream(saveFile));System.out.println("download file "+directory + "/" +downloadFile + " from host " + sshSession.getHost());}/*** 下載文件* @param src* @param dst* @throws Exception*/@SuppressWarnings("unchecked")public void downloadDir(String src, File dst) throws Exception {try {sftp.cd(src);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}dst.mkdirs();Vector<LsEntry> files = sftp.ls(src);for (LsEntry lsEntry : files) {if (lsEntry.getFilename().equals(".") || lsEntry.getFilename().equals("..")) {continue;}if (lsEntry.getLongname().startsWith("d")) {downloadDir(src + "/" + lsEntry.getFilename(), new File(dst, lsEntry.getFilename()));} else {download(src, lsEntry.getFilename(), new File(dst, lsEntry.getFilename()));}}}/*** 刪除文件* @param directory* @param deleteFile* @throws SftpException*/public void delete(String directory, String deleteFile) throws SftpException {sftp.cd(directory);sftp.rm(deleteFile);}/*** 列出目錄下的文件* @param directory* @return* @throws SftpException*/public Vector listFiles(String directory) throws SftpException {return sftp.ls(directory);}public Session getSshSession() {return sshSession;}public ChannelSftp getSftp() {return sftp;} }

在這個工具類里,我自己在這個類的基礎(chǔ)之上往里面加了一個方法,利用流上傳文件

//利用流上傳文件 fileNamepublic void uploadfileInputStream(MultipartFile file, String directory, String fileName) throws Exception {sftp.cd(directory);sftp.put(file.getInputStream(),fileName);}

這里要注意的是form表單中一定要添加 enctype="multipart/form-data"不然在后臺接收不到文件流

<form class="form-horizontal" action="/upload" name="upload" id="form" method="post" enctype="multipart/form-data"><input type="file" name="filename" id="filename"/><br/><input type="submit" value="提交" /><br/> </form>

?后端Controller

@RequestMapping("/upload")public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("fileName") String fileName) throws Exception {if(file.isEmpty()||fileName.isEmpty()){new Exception("未接收到指定參數(shù)");return "";}else{SftpsEntity sftpsAll = service.findAll();try {sftps = new Sftps();//連接服務(wù)器sftps.connect("192.168.1.154", 22,"root","123456");//上傳到服務(wù)器的位置sftps.uploadfileInputStream(file, "/", fileName);} catch (Exception e) {e.printStackTrace();} finally {sftps.disconnect();}return "{message:\"上傳成功\"}";}

?uploadfileInputStream()三個參數(shù)分別代表

file 文件流(文件),

/? 代表存在服務(wù)器的根目錄下,

fileName 文件全名稱,包括后綴,三者缺一不可!

總結(jié)

以上是生活随笔為你收集整理的Springboot通过SFTP上传文件到服务器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。