當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Springboot通过SFTP上传文件到服务器
生活随笔
收集整理的這篇文章主要介紹了
Springboot通过SFTP上传文件到服务器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
流程是這樣的:
前端選擇文件上傳-------->調用后臺接口,后臺連接服務器(Linux)--------->上傳成功
?前端無論是通過ajax,還是form表單直接提交都可以,這里暫時以form方式提交 這里需要依靠一個Sftps的工具類
先導入依賴
Sftps.java:
public final class Sftps {private static final Logger log = LoggerFactory.getLogger(Sftps.class);private Session sshSession;private ChannelSftp sftp;/*** 連接sftp服務器* @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服務器* @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();//設置密鑰和密碼if (!StringUtils.isEmpty(privateKey)) {if (!StringUtils.isEmpty(passphrase)) {//設置帶口令的密鑰jsch.addIdentity(privateKey, passphrase);} else {//設置不帶口令的密鑰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;} }在這個工具類里,我自己在這個類的基礎之上往里面加了一個方法,利用流上傳文件
//利用流上傳文件 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("未接收到指定參數");return "";}else{SftpsEntity sftpsAll = service.findAll();try {sftps = new Sftps();//連接服務器sftps.connect("192.168.1.154", 22,"root","123456");//上傳到服務器的位置sftps.uploadfileInputStream(file, "/", fileName);} catch (Exception e) {e.printStackTrace();} finally {sftps.disconnect();}return "{message:\"上傳成功\"}";}?uploadfileInputStream()三個參數分別代表
file 文件流(文件),
/? 代表存在服務器的根目錄下,
fileName 文件全名稱,包括后綴,三者缺一不可!
總結
以上是生活随笔為你收集整理的Springboot通过SFTP上传文件到服务器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CAD如何绘制A0/A1/A2/A3/A
- 下一篇: 从荣耀A2手环看穿戴设备设计