1、需要在pom.xml文件中引用jsch的依賴:
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.54</version> </dependency>
2、ajax異步提交請求:
var uploadImage = function () { var file = document.getElementById("file").files[0]; var formData = new FormData(); formData.append('file', file); $.ajax({ type: "post", dataType: "json", data: formData, url: "catalog/uploadImage", contentType: false, processData: false, mimeType: "multipart/form-data", success: function (data) { if (data.code > 0) { alert("操作成功"); } else { alert(data.message); } }, error: function () { alert("出錯了,請聯系管理員!"); } }); }
3、后端接收請求方法:
@ResponseBody @RequestMapping("/uploadImage") public Object uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException { HotelImageVo imageVo = new HotelImageVo(); if (file == null) { imageVo.setCode(0); imageVo.setMessage("請先選擇圖片!"); return JSON.toJSONString(imageVo); } double fileSize = file.getSize(); System.out.println("文件的大小是" + fileSize); //拓展的目錄,hotelId不為空則使用hotelId作為目錄的一部分 String extendDir = "ranklist/"; String fileName = file.getOriginalFilename();// 文件原名稱 // 判斷文件類型 String type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null; if (type != null) {// 判斷文件類型是否為空 if ("JPEG".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) { // 項目在容器中實際發布運行的根路徑 String realPath = request.getSession().getServletContext().getRealPath("/"); String dirPath = "/upload/" + extendDir; // 自定義的文件名稱 fileName = UUID.randomUUID().toString() + "." + type; String localPath = realPath + dirPath + fileName; File newFile = new File(localPath); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } //保存本地文件 file.transferTo(newFile); //上傳遠程文件 SFTPUtils sftp = new SFTPUtils(); sftp.upload(localPath, extendDir, fileName); //刪除本地文件 newFile.delete(); } else { imageVo.setCode(0); imageVo.setMessage("圖片格式必須是png、jpg或jpeg!"); return JSON.toJSONString(imageVo); } } else { imageVo.setCode(0); imageVo.setMessage("文件類型為空!"); return JSON.toJSONString(imageVo); } imageVo.setCode(1); String newFilePath = ServerConfig.newUrl + extendDir + fileName; imageVo.setMessage(newFilePath); return JSON.toJSONString(imageVo); }
4、通過SFTP把圖片上傳服務器使用的工具類:
public class SFTPUtils { private ChannelSftp sftp; private Session session; private String sftpPath; public SFTPUtils() { this.connectServer("服務器IP", 22, "用戶名", "密碼", "需要保存文件的文件夾路徑"); } public SFTPUtils(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) { this.connectServer(ftpHost, ftpPort, ftpUserName, ftpPassword, sftpPath); } private void connectServer(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) { try { this.sftpPath = sftpPath; // 創建JSch對象 JSch jsch = new JSch(); // 根據用戶名,主機ip,端口獲取一個Session對象 session = jsch.getSession(ftpUserName, ftpHost, ftpPort); if (ftpPassword != null) { // 設置密碼 session.setPassword(ftpPassword); } Properties configTemp = new Properties(); configTemp.put("StrictHostKeyChecking", "no"); // 為Session對象設置properties session.setConfig(configTemp); // 設置timeout時間 session.setTimeout(60000); session.connect(); // 通過Session建立鏈接 // 打開SFTP通道 sftp = (ChannelSftp) session.openChannel("sftp"); // 建立SFTP通道的連接 sftp.connect(); } catch (JSchException e) { e.printStackTrace(); } } /** * 斷開SFTP Channel、Session連接 */ public void closeChannel() { try { if (sftp != null) { sftp.disconnect(); } if (session != null) { session.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } /** * 上傳文件 * * @param localFile 本地文件 * @param remotePath 遠程文件 * @param fileName 文件名稱 */ public void upload(String localFile, String remotePath, String fileName) { try { if (remotePath != null && !"".equals(remotePath)) { remotePath = sftpPath + remotePath; createDir(remotePath); sftp.put(localFile, (remotePath + fileName), ChannelSftp.OVERWRITE); sftp.quit(); } } catch (SftpException e) { e.printStackTrace(); } } /** * 下載文件 * * @param remotePath 遠程文件 * @param fileName 文件名稱 * @param localFile 本地文件 */ public void download(String remotePath, String fileName, String localFile) { try { remotePath = sftpPath + remotePath; if (remotePath != null && !"".equals(remotePath)) { sftp.cd(remotePath); } sftp.get((remotePath + fileName), localFile); sftp.quit(); } catch (SftpException e) { e.printStackTrace(); } } /** * 刪除文件 * * @param remotePath 要刪除文件所在目錄 */ public void delete(String remotePath) { try { if (remotePath != null && !"".equals(remotePath)) { remotePath = sftpPath + remotePath; sftp.rm(remotePath); } } catch (Exception e) { e.printStackTrace(); } } /** * 創建一個文件目錄 */ public void createDir(String createpath) { try { if (isDirExist(createpath)) { this.sftp.cd(createpath); return; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if (isDirExist(filePath.toString())) { sftp.cd(filePath.toString()); } else { // 建立目錄 sftp.mkdir(filePath.toString()); // 進入並設置為當前目錄 sftp.cd(filePath.toString()); } } this.sftp.cd(createpath); } catch (SftpException e) { throw new SystemException("創建路徑錯誤:" + createpath); } } /** * 判斷目錄是否存在 */ public boolean isDirExist(String directory) { boolean isDirExistFlag = false; try { SftpATTRS sftpATTRS = sftp.lstat(directory); isDirExistFlag = true; return sftpATTRS.isDir(); } catch (Exception e) { if (e.getMessage().toLowerCase().equals("no such file")) { isDirExistFlag = false; } } return isDirExistFlag; } }