Linux云服務(wù)器搭建SFTP服務(wù)器圖片服務(wù)器的操作
首先大家可以先了解一下SFTP和FTP協(xié)議的區(qū)別,這里我就不贅述了。
Sftp 默認(rèn)監(jiān)聽端口22 Ftp協(xié)議默認(rèn)監(jiān)聽端口21 本質(zhì)沒什么區(qū)別都是基于文件傳輸協(xié)議。前者安全性能高,后者效率高。
下面進(jìn)入正題:
一,確保你的Linux 賬號(hào)能連接,sftp默認(rèn)就是Linux root賬號(hào)密碼這里就是你的管理員賬號(hào)用戶名和密碼。一般這個(gè)密碼Sftp就直接連就行了不用改的都。下面看看Xftp
連接成功了說明沒有問題。
二,通過如果是阿里云服務(wù)器一定把防火墻和安全組都打開,以免出現(xiàn)其他問題還有一個(gè)防火墻
博主這里是maven項(xiàng)目直接把包發(fā)給你們(如果是web項(xiàng)目去官網(wǎng)下載jar包)
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.49</version></dependency>四,配置包下好過后現(xiàn)在使用工具類上傳連接啦。(這里可以注解配置文件自行配置)
public class SFTPInfo { public static final String SFTP_REQ_HOST = '000.00.00.00';//云服務(wù)器ip public static final String SFTP_REQ_USERNAME = '00t'; // 用戶名 public static final String SFTP_REQ_PASSWORD = '00'; //密碼 public static final int SFTP_DEFAULT_PORT = 22; //端口 public static String basePath='/usr/games/images'; // 文件在服務(wù)器端保存的主目錄 (文件上傳路徑這是) public static String baseUrl='https://##.##.com/images'; //線上域名訪問指定nginx訪問路徑 (這里路徑很關(guān)鍵)}
這里的用戶和密碼都是你自己的服務(wù)器用戶名和密碼。
五,SFTP上傳工具類:import java.io.InputStream;import java.util.Properties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.jcraft.jsch.Channel;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.JSch;import com.jcraft.jsch.JSchException;import com.jcraft.jsch.Session;import com.jcraft.jsch.SftpException; public class SftpUtils { private static final Logger LOG = LoggerFactory.getLogger(SftpUtils.class); /** * 參考實(shí)例 * * @param args */ public Channel getChannel(Session session) {Channel channel = null;try { channel = session.openChannel('sftp'); channel.connect(); LOG.info('get Channel success!');} catch (JSchException e) { LOG.info('get Channel fail!', e);}return channel; } public Session getSession(String host, int port, String username, final String password) {Session session = null;try { JSch jsch = new JSch(); jsch.getSession(username, host, port); session = jsch.getSession(username, host, port); session.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put('StrictHostKeyChecking', 'no'); session.setConfig(sshConfig); session.connect(); LOG.info('Session connected!');} catch (JSchException e) { LOG.info('get Channel failed!', e);}return session; } /** * 創(chuàng)建文件夾 * * @param sftp * @param dir * 文件夾名稱 */ public void mkdir(ChannelSftp sftp, String dir) {try { sftp.mkdir(dir); System.out.println('創(chuàng)建文件夾成功!');} catch (SftpException e) { System.out.println('創(chuàng)建文件夾失敗!'); e.printStackTrace();} } /** * @param sftp * @param dir * 上傳目錄 * @param file * 上傳文件 * @return */ public Boolean uploadFile(ChannelSftp sftp, String dir, InputStream file,String fileName) {Boolean flag = false;try { sftp.cd(dir); if (file != null) {sftp.put(file, fileName);flag=true;return flag; } else {flag=false;return flag; }} catch (Exception e) { flag=false; return flag;} } /** * 下載文件 * * @param directory * 下載目錄 * @param downloadFile * 下載的文件 * @param saveFile * 存在本地的路徑 * @param sftp */ public String download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {String result = '';try { sftp.cd(directory); sftp.get(downloadFile, saveFile); result = '下載成功!';} catch (Exception e) { result = '下載失敗!'; LOG.info('下載失敗!', e); ;}return result; } /** * 刪除文件 * * @param directory * 要?jiǎng)h除文件所在目錄 * @param deleteFile * 要?jiǎng)h除的文件 * @param sftp */ public String delete(String directory, String deleteFile, ChannelSftp sftp) {String result = '';try { sftp.cd(directory); sftp.rm(deleteFile); result = '刪除成功!';} catch (Exception e) { result = '刪除失敗!'; LOG.info('刪除失敗!', e);}return result; } private void closeChannel(Channel channel) {if (channel != null) { if (channel.isConnected()) {channel.disconnect(); }} } private void closeSession(Session session) {if (session != null) { if (session.isConnected()) {session.disconnect(); }} } public void closeAll(ChannelSftp sftp, Channel channel, Session session) {try { closeChannel(sftp); closeChannel(channel); closeSession(session);} catch (Exception e) { LOG.info('closeAll', e);} }}
工具類不需要修改直接使用即可。
還有一個(gè)隨機(jī)生成文件名稱的工具類也發(fā)給大家
import java.util.Random; public class IDUtils { /** * 生成隨機(jī)圖片名 */ public static String genImageName() {//取當(dāng)前時(shí)間的長(zhǎng)整形值包含毫秒long millis = System.currentTimeMillis(); //加上三位隨機(jī)數(shù)Random random = new Random();int end3 = random.nextInt(999);//如果不足三位前面補(bǔ)0String str = millis + String.format('%03d', end3);return str; }}六,后臺(tái)請(qǐng)求方法看看
博主這里用了 Clipboard 上傳,參數(shù)不支持序列化所以就一個(gè)個(gè)接受了,很多@RequestParam('file') MultipartFile file,加其他參數(shù)加上是post請(qǐng)求方式有的會(huì)報(bào)錯(cuò)把post請(qǐng)求方法找不到,這個(gè)問題不影響。
@Log('網(wǎng)站案例上傳信息')@ResponseBody@PostMapping('/upload')@RequiresPermissions('common:cases:upload')R upload(@RequestParam('file') MultipartFile file,@RequestParam('ctitle') String ctitle, @RequestParam('cmessage') String cmessage, @RequestParam('casetroduction') String casetroduction,@RequestParam('strdate') Date strdate,@RequestParam('stpdate') Date stpdate, @RequestParam('credate') Date credate,HttpServletRequest request) throws ParseException, IOException { String oldName = file.getOriginalFilename(); //使用IDUtils工具類生成新的文件名,新文件名 = newName + 文件后綴 String newName = IDUtils.genImageName(); newName = newName + oldName.substring(oldName.lastIndexOf('.')); SftpUtils ft = new SftpUtils(); //通過SFtoInfo 參數(shù)連接傳入?yún)?shù)即可 Session s = ft.getSession(SFTPInfo.SFTP_REQ_HOST,SFTPInfo.SFTP_DEFAULT_PORT, SFTPInfo.SFTP_REQ_USERNAME,SFTPInfo.SFTP_REQ_PASSWORD); Channel channel = ft.getChannel(s); ChannelSftp sftp = (ChannelSftp)channel; Boolean upload = ft.uploadFile(sftp,SFTPInfo.basePath, file.getInputStream(),newName); if(upload){ //上傳成功關(guān)閉信息 ft.closeAll(sftp, channel, s); //關(guān)閉連接 CasesDO cases=new CasesDO(); cases.setCtitle(ctitle);// 這里很重要 這是訪問路徑寫入到數(shù)據(jù)庫(kù)的路徑加線上域名訪問圖片的路徑,博主這里加了ssl證書 // https://**.**.com/images newName=文件名圖片 cases.setCaseimg(SFTPInfo.baseUrl + '/' + newName); cases.setCasetroduction(casetroduction); cases.setStpdate(stpdate); cases.setCredate(credate); cases.setStrdate(strdate); cases.setCmessage(cmessage); if (casesService.save(cases) > 0) { return R.ok('上傳成功'); } }else { return R.error('上傳error'); } return R.error();}
看看前臺(tái)js------請(qǐng)求參數(shù)大家可以換成HashMap但是后臺(tái)會(huì)用Object轉(zhuǎn)其他類型轉(zhuǎn)倆次
var clipboard = new Clipboard(’button.copy’, { text: function (trigger) {layer.msg(’文件路徑已復(fù)制到粘貼板’);return $(trigger).attr(’url’); }});layui.use(’upload’, function () { var upload = layui.upload; //執(zhí)行實(shí)例 upload.render({elem: ’#test1’, //綁定元素url: ’/common/cases/upload’, //上傳接口size: 100000,// auto: false,accept: ’file’,//bindAction: ’#submits’,before: function (obj) { //obj參數(shù)包含的信息,跟 choose回調(diào)完全一致。其中輸入向后臺(tái)傳輸?shù)膮?shù) layer.load(); this.data = {ctitle: $(’#ctitle’).val(),cmessage: $(’#cmessage’).val() ,casetroduction: $(’#casetroduction’).val(),strdate: $(’#strdate’).val(),stpdate: $(’#stpdate’).val(),credate: $(’#credate’).val(), };},done: function (r) { parent.layer.msg(r.msg); parent.reLoad(); var index = parent.layer.getFrameIndex(window.name); // 獲取窗口索引 parent.layer.close(index);},error: function (r) { layer.msg(r.msg);} });});
成功后報(bào)存到數(shù)據(jù)庫(kù)-------
這里上傳成功過后圖片在SftpInfo類的 /usr/games/images路徑也就是服務(wù)器路徑地址
上傳成功后就在這個(gè)路徑了。如果不是root用戶一定要給權(quán)限 chmod 777 /usr/gemes/
八,下面就是nginx配置 (這里nginx我就不說安裝方法自行百度)最關(guān)鍵一步這里就是通過這個(gè)nginx路徑指向到上傳圖片路徑,autoIndex on;是開啟瀏覽, alias 是直接指向
啟動(dòng)nginx 刷新一下配置
/usr/local/nginx/sbin/nginx -s reload
九,訪問一下圖片大工告成。博主重新上傳了一張圖片
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. rsync結(jié)合 inotfiy 實(shí)現(xiàn)實(shí)時(shí)備份的問題2. mac程序沒反應(yīng)怎么辦 mac強(qiáng)制關(guān)閉程序的方法3. grub2引導(dǎo)freebsd詳解4. FreeBSD10安裝內(nèi)核源代碼方法講解5. 世界上最流行的操作系統(tǒng)不是Linux或者Windows,而是MINIX6. 更新FreeBSD Port Tree的幾種方法小結(jié)7. 支持深色 / 淺色模式,微軟 Win11 Build 25281 為“產(chǎn)品密鑰”窗口啟用新界面8. 去掉系統(tǒng)快捷方式箭頭的途徑——修改注冊(cè)表9. Mac版steam錯(cuò)誤代碼118怎么解決?Mac版steam錯(cuò)誤代碼118解決教程10. freebsd 服務(wù)器 ARP綁定腳本
