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;
} }

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. 用JavaScript带你体验V8引擎解析标识符

    上一篇讲了字符串的解析过程,这一篇来讲讲标识符(IDENTIFIER)的解析. 先上知识点,标识符的扫描分为快解析和慢解析,一旦出现Ascii编码大于127的字符或者转义字符,会进入慢解析,略微影响性 ...

  2. 获取apache ignite缓存中的数据行数少于实际行数

    我将ignite项目打包放到linux下,在linux下获取window中存放在oracle数据库中的数据,linux服务器作为ignite的服务端节点,我在本地启动tomact,作为ignite客户 ...

  3. Object.entries和Object.fromEntries

    语法 Object.entries(obj) 参数 obj 可以返回其可枚举属性的键值对的对象. 返回值 给定对象自身可枚举属性的键值对数组 语法 Object.fromEntries(iterabl ...

  4. MySQL单表最大记录数不能超过多少?

    MySQL单表最大记录数不能超过多少? 很多人困惑这个问题.其实,MySQL本身并没有对单表最大记录数进行限制,这个数值取决于你的操作系统对单个文件的限制本身. 从性能角度来讲,MySQL单表数据不要 ...

  5. android studio学习----The project encoding (windows-1252) does not match the encoding specified in the Gradle build files (UTF-8)

    Warning:The project encoding (windows-1252) does not match the encoding specified in the Gradle buil ...

  6. js 数组 添加或删除 元素 splice 创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素 filter

    里面可以用 箭头函数 splice         删除 增加 数组 中元素 操作数组 filter 创建新数组  检查指定数组中符合条件的所有元素

  7. Nginx服务加到systemctl

    当我们编译安装nginx服务后,可以用手执行启动脚本也可以作为服务的形式运行. 添加启动文件:vim /usr/lib/systemd/system/nginx.service [Unit] Desc ...

  8. Window 2003 IIS + MySQL + PHP + Zend 环境配置

    图文详解 下载 Windows 2003 Zend, PHP, PHPMyadmin 与 MySQL Windows 2003 安装包中包含了 Zend,PHP 5.2.17,PHPWind8.7 和 ...

  9. elastalert基本配置说明

    elastalert 配置语法: 简单rule规则: es_host,es_port:查询elasticsearch集群 name: 规则的唯一名称.如果相同,则elastalert不会启动. typ ...

  10. elastalert docker安装

    基于对elasticsearch中数据监控需要,我尝试了sentinl和elastalert两款工具.虽然elastalert是纯文本,但易配置管理.elk自带的watch需要付费才可使用. 6.2x ...