1、需要在pom.xml文件中引用jsch的依赖:

  1. <dependency>
  2. <groupId>com.jcraft</groupId>
  3. <artifactId>jsch</artifactId>
  4. <version>0.1.54</version>
  5. </dependency>

2、ajax异步提交请求:

  1. var uploadImage = function () {
  2. var file = document.getElementById("file").files[0];
  3. var formData = new FormData();
  4. formData.append('file', file);
  5.  
  6. $.ajax({
  7. type: "post",
  8. dataType: "json",
  9. data: formData,
  10. url: "catalog/uploadImage",
  11. contentType: false,
  12. processData: false,
  13. mimeType: "multipart/form-data",
  14. success: function (data) {
  15. if (data.code > 0) {
  16. alert("操作成功");
  17. } else {
  18. alert(data.message);
  19. }
  20. },
  21. error: function () {
  22. alert("出错了,请联系管理员!");
  23. }
  24. });
  25. }

3、后端接收请求方法:

  1.   @ResponseBody
  2. @RequestMapping("/uploadImage")
  3. public Object uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
  4. HotelImageVo imageVo = new HotelImageVo();
  5.  
  6. if (file == null) {
  7. imageVo.setCode(0);
  8. imageVo.setMessage("请先选择图片!");
  9. return JSON.toJSONString(imageVo);
  10. }
  11.  
  12. double fileSize = file.getSize();
  13. System.out.println("文件的大小是" + fileSize);
  14.  
  15. //拓展的目录,hotelId不为空则使用hotelId作为目录的一部分
  16. String extendDir = "ranklist/";
  17.  
  18. String fileName = file.getOriginalFilename();// 文件原名称
  19. // 判断文件类型
  20. String type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
  21. if (type != null) {// 判断文件类型是否为空
  22. if ("JPEG".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
  23. // 项目在容器中实际发布运行的根路径
  24. String realPath = request.getSession().getServletContext().getRealPath("/");
  25. String dirPath = "/upload/" + extendDir;
  26. // 自定义的文件名称
  27. fileName = UUID.randomUUID().toString() + "." + type;
  28. String localPath = realPath + dirPath + fileName;
  29. File newFile = new File(localPath);
  30. if (!newFile.getParentFile().exists()) {
  31. newFile.getParentFile().mkdirs();
  32. }
  33. //保存本地文件
  34. file.transferTo(newFile);
  35.  
  36. //上传远程文件
  37. SFTPUtils sftp = new SFTPUtils();
  38. sftp.upload(localPath, extendDir, fileName);
  39.  
  40. //删除本地文件
  41. newFile.delete();
  42. } else {
  43. imageVo.setCode(0);
  44. imageVo.setMessage("图片格式必须是png、jpg或jpeg!");
  45. return JSON.toJSONString(imageVo);
  46. }
  47. } else {
  48. imageVo.setCode(0);
  49. imageVo.setMessage("文件类型为空!");
  50. return JSON.toJSONString(imageVo);
  51. }
  52.  
  53. imageVo.setCode(1);
  54. String newFilePath = ServerConfig.newUrl + extendDir + fileName;
  55. imageVo.setMessage(newFilePath);
  56. return JSON.toJSONString(imageVo);
  57. }

4、通过SFTP把图片上传服务器使用的工具类:

  1. public class SFTPUtils {
  2.  
  3. private ChannelSftp sftp;
  4. private Session session;
  5. private String sftpPath;
  6.  
  7. public SFTPUtils() {
  8. this.connectServer("服务器IP", 22, "用户名", "密码", "需要保存文件的文件夹路径");
  9. }
  10.  
  11. public SFTPUtils(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) {
  12. this.connectServer(ftpHost, ftpPort, ftpUserName, ftpPassword, sftpPath);
  13. }
  14.  
  15. private void connectServer(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) {
  16. try {
  17. this.sftpPath = sftpPath;
  18.  
  19. // 创建JSch对象
  20. JSch jsch = new JSch();
  21. // 根据用户名,主机ip,端口获取一个Session对象
  22. session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
  23. if (ftpPassword != null) {
  24. // 设置密码
  25. session.setPassword(ftpPassword);
  26. }
  27. Properties configTemp = new Properties();
  28. configTemp.put("StrictHostKeyChecking", "no");
  29. // 为Session对象设置properties
  30. session.setConfig(configTemp);
  31. // 设置timeout时间
  32. session.setTimeout(60000);
  33. session.connect();
  34. // 通过Session建立链接
  35. // 打开SFTP通道
  36. sftp = (ChannelSftp) session.openChannel("sftp");
  37. // 建立SFTP通道的连接
  38. sftp.connect();
  39. } catch (JSchException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43.  
  44. /**
  45. * 断开SFTP Channel、Session连接
  46. */
  47. public void closeChannel() {
  48. try {
  49. if (sftp != null) {
  50. sftp.disconnect();
  51. }
  52. if (session != null) {
  53. session.disconnect();
  54. }
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58. }
  59.  
  60. /**
  61. * 上传文件
  62. *
  63. * @param localFile 本地文件
  64. * @param remotePath 远程文件
  65. * @param fileName 文件名称
  66. */
  67. public void upload(String localFile, String remotePath, String fileName) {
  68. try {
  69. if (remotePath != null && !"".equals(remotePath)) {
  70. remotePath = sftpPath + remotePath;
  71. createDir(remotePath);
  72. sftp.put(localFile, (remotePath + fileName), ChannelSftp.OVERWRITE);
  73. sftp.quit();
  74. }
  75. } catch (SftpException e) {
  76. e.printStackTrace();
  77. }
  78. }
  79.  
  80. /**
  81. * 下载文件
  82. *
  83. * @param remotePath 远程文件
  84. * @param fileName 文件名称
  85. * @param localFile 本地文件
  86. */
  87. public void download(String remotePath, String fileName, String localFile) {
  88. try {
  89. remotePath = sftpPath + remotePath;
  90. if (remotePath != null && !"".equals(remotePath)) {
  91. sftp.cd(remotePath);
  92. }
  93. sftp.get((remotePath + fileName), localFile);
  94. sftp.quit();
  95. } catch (SftpException e) {
  96. e.printStackTrace();
  97. }
  98. }
  99.  
  100. /**
  101. * 删除文件
  102. *
  103. * @param remotePath 要删除文件所在目录
  104. */
  105. public void delete(String remotePath) {
  106. try {
  107. if (remotePath != null && !"".equals(remotePath)) {
  108. remotePath = sftpPath + remotePath;
  109. sftp.rm(remotePath);
  110. }
  111. } catch (Exception e) {
  112. e.printStackTrace();
  113. }
  114. }
  115.  
  116. /**
  117. * 创建一个文件目录
  118. */
  119. public void createDir(String createpath) {
  120. try {
  121. if (isDirExist(createpath)) {
  122. this.sftp.cd(createpath);
  123. return;
  124. }
  125. String pathArry[] = createpath.split("/");
  126. StringBuffer filePath = new StringBuffer("/");
  127. for (String path : pathArry) {
  128. if (path.equals("")) {
  129. continue;
  130. }
  131. filePath.append(path + "/");
  132. if (isDirExist(filePath.toString())) {
  133. sftp.cd(filePath.toString());
  134. } else {
  135. // 建立目录
  136. sftp.mkdir(filePath.toString());
  137. // 进入并设置为当前目录
  138. sftp.cd(filePath.toString());
  139. }
  140. }
  141. this.sftp.cd(createpath);
  142. } catch (SftpException e) {
  143. throw new SystemException("创建路径错误:" + createpath);
  144. }
  145. }
  146.  
  147. /**
  148. * 判断目录是否存在
  149. */
  150. public boolean isDirExist(String directory) {
  151. boolean isDirExistFlag = false;
  152. try {
  153. SftpATTRS sftpATTRS = sftp.lstat(directory);
  154. isDirExistFlag = true;
  155. return sftpATTRS.isDir();
  156. } catch (Exception e) {
  157. if (e.getMessage().toLowerCase().equals("no such file")) {
  158. isDirExistFlag = false;
  159. }
  160. }
  161. return isDirExistFlag;
  162. }
  163.  
  164. }

Java 通过SFTP上传图片功能的更多相关文章

  1. JAVA 上传图片功能

    前后端实现上传图片功能(JAVA代码) 1.前端大概 请求头必须为AJAX请求头: 'X-Requested-With': 'XMLHttpRequest' 一般是指网页中存在的Content-Typ ...

  2. 配置Django-TinyMCE组件支持上传图片功能

    Django自带的Admin后台,好用,TinyMCE作为富文本编辑器,也蛮好用的,这两者结合起来在做博客的时候很方便(当然博客可能更适合用Markdown来写),但是Django-TinyMCE这个 ...

  3. MVC ueditor的使用(实现上传图片功能)

    之前使用ckeditor不能实现上传图片功能,只要是我不知道怎么使用啦o( ̄ε ̄*),然后就换了ueditor~~,可以实现上传图片功能啦~\(≧▽≦)/~~ 下面是我的步骤:去官网下载最新版uedi ...

  4. aspx页面中用Input 标签实现上传图片功能

    实现上传图片功能需单独的建立一个aspx页面, 其中前台页面需要注意两点: a)实现上传功能的input的type="file" b)设置请求报文头为 enctype=" ...

  5. [转]JAVA实现SFTP实例

    http://www.cnblogs.com/chen1987lei/archive/2010/11/26/1888384.html 最近写的一个JAVA实现SFTP的实例: /** Created ...

  6. Java使用SFTP和FTP两种连接方式实现对服务器的上传下载 【我改】

    []如何区分是需要使用SFTP还是FTP? []我觉得: 1.看是否已知私钥. SFTP 和 FTP 最主要的区别就是 SFTP 有私钥,也就是在创建连接对象时,SFTP 除了用户名和密码外还需要知道 ...

  7. JAVA实现SFTP实例

    最近写的一个JAVA实现SFTP的实例: /* * Created on 2009-9-14 * Copyright 2009 by www.xfok.net. All Rights Reserved ...

  8. Java 基本数据类型 sizeof 功能

    Java 基本数据类型 sizeof 功能 来源 https://blog.csdn.net/ithomer/article/details/7310008 Java基本数据类型int     32b ...

  9. WCF实现上传图片功能

    初次学习实现WCF winform程序的通信,主要功能是实现图片的传输. 下面是实现步骤: 第一步: 首先建立一个类库项目TransferPicLib,导入wcf需要的引用System.Service ...

随机推荐

  1. css的尺寸、display的属性、以及浮动和清除浮动的方法

    css的尺寸width heightline-height 行高是由三部分构成,上间距 文本高度 下间距,且上下间距相等.所以文字居中.行高:一旦设置了行高,元素内部必须有内容.line-height ...

  2. 要什么 Photoshop,会这些 CSS 就够了

    标题党一时爽,一直标题党一直爽 还在上大学那会儿,我就喜欢玩 Photoshop.后来写网页的时候,由于自己太菜,好多花里胡哨的效果都得借助 Photoshop 实现,当时就特别希望 CSS 能像 P ...

  3. bugku——普通的二维码(进制转换)

    题目地址:http://ctf.bugku.com/files/5e480ecb178711e82bc847a208e15b32/misc80.zip 就一张二维码图片,用一些在线工具识别是乱码,用Q ...

  4. Direct Access to Video Encoding and Decoding

    来源:http://asciiwwdc.com/2014/sessions/513   Direct Access to Video Encoding and Decoding  Session 5 ...

  5. JVM参数最佳实践:元空间的初始大小和最大大小

    本文阅读时间大约4分钟. JVM加载类的时候,需要记录类的元数据,这些数据会保存在一个单独的内存区域内,在Java 7里,这个空间被称为永久代(Permgen),在Java 8里,使用元空间(Meta ...

  6. 找出所有文件最小可resize尺寸

    --找出所有文件最小可resize尺寸 SELECT a.file_id, CEIL( ( NVL( hwm,1 ) * blksize ) / 1024 / 1024 ) smallest_M, C ...

  7. Bean的一生(Bean的生命周期)

    1. 什么是Bean? Bean是spring中组成应用程序的主体及由spring IoC容器所管理的对象(IoC容器初始化.装配及管理的对象).如果把spring比作一座大型工厂,那么bean就是该 ...

  8. PAT 乙级 1032.挖掘机技术哪家强 C++/Java

    题目来源 为了用事实说明挖掘机技术到底哪家强,PAT 组织了一场挖掘机技能大赛.现请你根据比赛结果统计出技术最强的那个学校. 输入格式: 输入在第 1 行给出不超过 1 的正整数 N,即参赛人数.随后 ...

  9. 查看mysql连接数和状态

    查看MySQL连接数 登录到MySQL命令行,使用如下命令可以查看当前处于连接未关闭状态的进程列表: show full processlist; 若不加上full选项,则最多显示100条记录. 若以 ...

  10. python 数据库小测试

    1.整理博客 2.详细解释下列mysql执行语句的每个参数与参数值的含义 ​ mysql -hlocalhost -P3306 -uroot -proot # mysql (连接数据库) # hloc ...