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

最新文章

  1. 2012 Multi-University Training Contest 9 / hdu4389
  2. mysql取前几行数据limit用法
  3. 对称加密之AES、压缩解压以及压缩加密解密解压综合实战
  4. 【转】为什么很多看起来不是很复杂的网站,比如 Facebook、淘宝,都需要大量顶尖高手来开发?
  5. Erlang练习-UDP
  6. Redis:安装
  7. 实现html转Xml
  8. jq中的css-Dom
  9. (译)Windsor入门教程---第四部分 整合
  10. java课程设计——猜数游戏
  11. LKD: Chapter 8 Bottom Halves and Deferring Work
  12. Macaca自动化工具之uirecorder脚本录制
  13. Java如何调取创蓝253短信验证码
  14. jmeter完成md5加密的接口请求参数
  15. C++的qsort函数
  16. vue-awesome-swiper 水平滚动异常
  17. NSGA-II入门C1
  18. python获取esxi的磁盘使用率信息
  19. 搭建基于MySQL的读写分离工具Amoeba
  20. JWT验证

热门文章

  1. nginx 配置处理静态资源
  2. UNION ALL \UNION
  3. .NetCore使用NLog写入数据库总结
  4. mvc5 源码解析2-2 mvchandler的执行
  5. mvc控制器接收ajax传送的数据
  6. 1.Shell特殊位置变量
  7. idea跳转到指定行列快捷键
  8. thinkphp5连接sql server
  9. django modelformse批量编辑 查询学生班级成绩
  10. 葫芦娃团队对火鸡堂、基于云的胜利冲锋队团队的Beta产品测试报告