First of all, you can understand the difference between SFTP and FTP protocols. I will not go into details here. The default listening port for Sftp is 22. The default listening port for FTP is 21. There is no essential difference between them. They are both based on file transfer protocols. The former has high safety performance, while the latter has high efficiency. Let’s get to the point: First, make sure your Linux account can connect. The default password for sftp is the Linux root account password.This is your administrator account username and password. Generally, you can just connect to Sftp with this password without changing it. Let's take a look at Xftp A successful connection indicates there is no problem. Second, if it is an Alibaba Cloud server, be sure to open both the firewall and security group to avoid other problemsThere is also a firewall Three, a very important step, upload through java JSCHThe blogger here is a Maven project and will send the package to you directly (if it is a web project, go to the official website to download the jar package) <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.49</version> </dependency> 4. After the configuration package is downloaded, use the tool class to upload the connection. (You can annotate the configuration file here to configure it yourself)public class SFTPInfo { public static final String SFTP_REQ_HOST = "000.00.00.00"; //Cloud server ip public static final String SFTP_REQ_USERNAME = "00t"; // Username public static final String SFTP_REQ_PASSWORD = "00"; // Password public static final int SFTP_DEFAULT_PORT = 22; // Port public static String basePath="/usr/games/images"; // The main directory where the file is saved on the server (this is the file upload path) public static String baseUrl="https://##.##.com/images"; //Online domain name access specifies the nginx access path (the path is critical here) } The user name and password here are your own server username and password. 5. SFTP upload tools: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); /** * Reference Example * * @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; } /** * Create Folder * * @param sftp * @param dir * Folder Name */ public void mkdir(ChannelSftp sftp, String dir) { try { sftp.mkdir(dir); System.out.println("Folder created successfully!"); } catch (SftpException e) { System.out.println("Failed to create folder!"); e.printStackTrace(); } } /** * @param sftp * @param dir * Upload directory * @param file * Upload 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; } } /** * Download File * * @param directory * Download directory * @param downloadFile * Downloaded file * @param saveFile * The local path * @param sftp */ public String download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) { String result = ""; try { sftp.cd(directory); sftp.get(downloadFile, saveFile); result = "Download successful!"; } catch (Exception e) { result = "Download failed!"; LOG.info("Download failed!", e); ; } return result; } /** * Delete Files* * @param directory * To delete the directory where the file is located* @param deleteFile * File to delete * @param sftp */ public String delete(String directory, String deleteFile, ChannelSftp sftp) { String result = ""; try { sftp.cd(directory); sftp.rm(deleteFile); result = "Deleted successfully!"; } catch (Exception e) { result = "Delete failed!"; LOG.info("Delete failed!", 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); } } } The tool class does not need to be modified and can be used directly. There is also a tool class for randomly generating file names that is also sent to everyone import java.util.Random; public class IDUtils { /** * Generate a random picture name */ public static String genImageName() { //Get the long integer value of the current time including milliseconds long millis = System.currentTimeMillis(); //Add three random numbers Random random = new Random(); int end3 = random.nextInt(999); //If there are less than three digits, add 0 in front String str = millis + String.format("%03d", end3); return str; } } 6. Background request methodThe blogger used Clipboard to upload here. The parameters do not support serialization, so they are accepted one by one. There are many @RequestParam("file") MultipartFile files. Adding other parameters and the post request method will result in an error that the post request method cannot be found. This problem does not affect it. @Log("Website case upload information") @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(); //Use IDUtils tool class to generate a new file name, new file name = newName + file suffix String newName = IDUtils.genImageName(); newName = newName + oldName.substring(oldName.lastIndexOf(".")); SftpUtils ft = new SftpUtils(); //Connect the parameters through SFtoInfo parameters 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){ //Close the upload successfully ft.closeAll(sftp, channel, s); //Close the connection CasesDO cases=new CasesDO(); cases.setCtitle(ctitle); // This is very important. This is the access path written into the database plus the online domain name to access the image. The blogger has added an SSL certificate here. // https://**.**.com/images newName=file name picture 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("Upload successful"); } }else { return R.error("upload error"); } return R.error(); } Look at the front-end js------the request parameters can be replaced with HashMap, but the back-end will use Object to convert to other types twice var clipboard = new Clipboard('button.copy', { text: function (trigger) { layer.msg('The file path has been copied to the clipboard'); return $(trigger).attr('url'); } }); layui.use('upload', function () { var upload = layui.upload; //Execute the example upload.render({ elem: '#test1', //Binding element url: '/common/cases/upload', //Upload interface size: 100000, // auto: false, accept: 'file', //bindAction: '#submits', before: function (obj) { //The information contained in the obj parameter is exactly the same as the choose callback. The input parameter layer.load() is transmitted to the background; 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); // Get window index parent.layer.close(index); }, error: function (r) { layer.msg(r.msg); } }); }); After success, save to the database------- 7. I won’t show the pageAfter the upload is successful, the image is in the /usr/games/images path of the SftpInfo class, which is the server path address. After the upload is successful, it will be in this path. If you are not the root user, you must give permissions chmod 777 /usr/gemes/ 8. The following is the nginx configuration (I will not tell you how to install nginx here, you can search on Baidu)The most critical step here is to point to the uploaded image path through this nginx path, autoIndex on; is to turn on browsing, alias is to point directly to Start nginx and refresh the configuration
9. Visit the pictures and you're done.The blogger re-uploaded a picture The above is my personal experience. I hope it can give you a reference. I also hope that you will support 123WORDPRESS.COM. You may also be interested in:
|
<<: Solutions to invalid is Null segment judgment and IFNULL() failure in MySql
>>: A detailed introduction to the use of block comments in HTML
We all know that Apache can easily set rewrites f...
Many times we want the server to run a script reg...
This article shares the specific code of js to ac...
MySQL 5.7.20 zip installation, the specific conte...
Note: The third method is only used in XSell and ...
MySQL supports many types of tables (i.e. storage...
Get the current date + time (date + time) functio...
This work uses the knowledge of front-end develop...
Many concepts in UI design may seem similar in wo...
I didn't intend to write this blog, but durin...
NULL and NOT NULL modifiers, DEFAULT modifier, AU...
A simple record of the database startup problems ...
View mysqlbinlog version mysqlbinlog -V [--versio...
<br />The information on web pages is mainly...
Table of contents Background Description Creating...