需要的jar包:

  去maven仓库自己搜索com.jcraft下载jar包

<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.49</version>
</dependency>

上传:

  ftp方式:

package com.sunsheen.jfids.studio.monitor.sender;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties; import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.sunsheen.jfids.studio.monitor.common.LogInfo;
/**
* 上传到远程服务器
* @author WangSong
*
*/
public class SendLogByFtp { /**
* 文件上传
* @param username 服务器用户名
* @param password 服务器密码
* @param address 服务器ip
* @param port 连接服务器的端口号(默认22)
* @param file 上传的文件
*/
public static void postFile(String username,String password,String address,int port,File file){
ChannelSftp sftp = null;
Channel channel = null;
Session sshSession = null;
try {
//创建连接
JSch jsch = new JSch();
sshSession = jsch.getSession(username, address, port);
sshSession.setPassword(password);
//获取session
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
//得到sftp
channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
//进入存放日志文件的目录
sftp.cd(LogInfo.SERVERS_RECIVE_FOLDER);
//上传
sftp.put(new FileInputStream(file), LogInfo.LOGS_ZIP_FILE_NAME);
System.out.println("上传成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭sftp信道
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
//关闭channel管道
if (channel != null) {
if (channel.isConnected()) {
channel.disconnect();
}
}
//关闭session
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
}
}
}
} }

点击查看源码

  http方式:

package com.sunsheen.jfids.studio.monitor.sender;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.core.runtime.Assert; /**
* 發送日誌文件到服務器 :需要将文件打包压缩
*
* @author WangSong
*
*/
public class SendLogByHttp { /**
* 发送日志文件
* @param url 远程地址
* @param param String类型的map数据,可以为空
* @param file 上传的文件
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String postFile(String url, Map<String, Object> param,
File file) throws ClientProtocolException, IOException { String res = null;
CloseableHttpClient httpClient = HttpClients.createDefault();//创建http客户端
HttpPost httppost = new HttpPost(url);
httppost.setEntity(getMutipartEntry(param, file));//设置发送的消息体 CloseableHttpResponse response = httpClient.execute(httppost);//发送消息到指定服务器 HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
res = EntityUtils.toString(entity, "UTF-8");
response.close();
} else {
res = EntityUtils.toString(entity, "UTF-8");
response.close();
throw new IllegalArgumentException(res);
}
return res;
} //得到当前文件实体
private static MultipartEntity getMutipartEntry(Map<String, Object> param,
File file) throws UnsupportedEncodingException {
Assert.isTrue(null == file, "文件不能为空!"); FileBody fileBody = new FileBody(file);//通过文件路径,得到文件体
FormBodyPart filePart = new FormBodyPart("file", fileBody);//格式化
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart(filePart); if(null != param){
Iterator<String> iterator = param.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
FormBodyPart field = new FormBodyPart(key, new StringBody(
(String) param.get(key)));
multipartEntity.addPart(field);
}
} return multipartEntity;
} }

点击查看

  socket方式:

package com.sunsheen.jfids.studio.monitor.sender;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket; /**
* 通過socket通信,發送文件
* @author WangSong
*
*/
public class SendLogBySocket { /**
* 文件上傳
* @param address 远程服务器地址
* @param port 远程服务器开放的端口号
* @param file 上传的文件
*/
public static void postFile(String address,int port,File file) {
Socket st = null;
BufferedOutputStream bos = null;
FileInputStream fis = null;
try {
//指定端口号
//InetAddress.getLocalHost();
st = new Socket(address,port);
//要上传文件位置
bos = new BufferedOutputStream(st.getOutputStream());
fis = new FileInputStream(file);
int len = 0;
byte b[] = new byte[1024];
//文件写入
while ((len = fis.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();
}
System.out.println("客户端上传完成!");
}
catch (IOException e) {
e.printStackTrace();
}finally {
try {
//关闭资源
fis.close();
bos.close();
st.close();
}catch (IOException e) {
e.printStackTrace();
}
}
} }

点击查看

下载

package com.sunsheen.jfids.studio.monitor.download;

import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.sunsheen.jfids.studio.monitor.HKMoniter;
import com.sunsheen.jfids.studio.monitor.HKMoniterFactory;
import com.sunsheen.jfids.studio.monitor.common.LogInfo; /**
* 下载服务器上的日志文件到本地
*
* @author WangSong
*
*/
public class DownloadLog {
private final static HKMoniter logger = HKMoniterFactory.getLogger(DownloadLog.class.getName()); public static void downloadLogs(String username, String password, String address,
int port) {
ChannelSftp sftp = null;
Channel channel = null;
Session sshSession = null;
try {
// 创建连接
JSch jsch = new JSch();
sshSession = jsch.getSession(username, address, port);
sshSession.setPassword(password);
// 获取session
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
// 得到sftp
channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
// 进入存放日志文件的目录
sftp.cd(LogInfo.SERVERS_RECIVE_FOLDER);
// 下载
sftp.get(LogInfo.SERVERS_RECIVE_FOLDER + "/"+LogInfo.LOGS_ZIP_FILE_NAME,LogInfo.LOCAL_LOG_PATH);
System.out.println("下载成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭sftp信道
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
// 关闭channel管道
if (channel != null) {
if (channel.isConnected()) {
channel.disconnect();
}
}
// 关闭session
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
}
}
}
} }

点击查看

上传文件到服务器指定位置 & 从服务器指定位置下载文件的更多相关文章

  1. spring mvc 图片上传,图片压缩、跨域解决、 按天生成文件夹 ,删除,限制为图片代码等相关配置

    spring mvc 图片上传,跨域解决 按天生成文件夹 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ ...

  2. Web---文件上传-用apache的工具处理、打散目录、简单文件上传进度

    我们需要先准备好2个apache的类: 上一个博客文章只讲了最简单的入门,现在来开始慢慢加深. 先过渡一下:只上传一个file项 index.jsp: <h2>用apache的工具处理文件 ...

  3. 使用递归方法实现,向FTP服务器上传整个目录结构、从FTP服务器下载整个目录到本地的功能

    我最近由于在做一个关于FTP文件上传和下载的功能时候,发现Apache FTP jar包没有提供对整个目录结构的上传和下载功能,只能非目录类型的文件进行上传和下载操作,后来我查阅很多网上的实现方法,再 ...

  4. kindeditor修改图片上传路径-使用webapi上传图片到图片服务器

    kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 在这里我着重介绍一些使用kindeditor修改图片上传路径并通过webapi上传图片到图片服务器的方案. 因为我使用的 ...

  5. 码云git使用一(上传本地项目到码云git服务器上)

    主要讲下如果将项目部署到码云git服务器上,然后使用studio导入git项目,修改本地代码后,并同步到码云git上面. 首先:我们在码云上注册账号并登陆.官网(https://git.oschina ...

  6. C# HTTP系列12 以form-data方式上传键值对集合到远程服务器

    系列目录     [已更新最新开发文章,点击查看详细] 使用multipart/form-data方式提交数据与普通的post方式有一定区别.multipart/form-data的请求头必须包含一个 ...

  7. PHP使用文件流下载文件方法(附:解决下载文件内容乱码问题)

    1.flush - 刷新输出缓冲 2.ob_clean - 清空(擦掉)输出缓冲区 此函数用来丢弃输出缓冲区中的内容. 此函数不会销毁输出缓冲区,而像 ob_end_clean() 函数会销毁输出缓冲 ...

  8. vue+element-ui upload图片上传前大小超过4m,自动压缩到指定大小,长宽

    最近项目需要实现一个需求,用户上传图片时,图片大小超过4M,长宽超过2000,需要压缩到400k,2000宽高.在git上找到一个不错的方法,把实现方法总结一下: 安装image-conversion ...

  9. linux学习 XShell上传、下载本地文件到linux服务器

    (一)通过命令行的方式 1.linux服务器端设置 在linux主机上,安装上传下载工具包rz及sz; 如果不知道你要安装包的具体名称,可以使用yum provides */name 进行查找系统自带 ...

  10. 【JAVAWEB学习笔记】29_文件的上传------commons-fileupload

    今天内容: 文件的上传------commons-fileupload 文件上传和下载的实质:文件的拷贝 文件上传:从本地拷贝到服务器磁盘上   客户端需要编写文件上传表单---->服务端需要编 ...

随机推荐

  1. 003.Nginx配置解析

    一 Nginx配置文件 1.1 Nginx主配置 Nginx主配置文件/etc/nginx/nginx.conf是一个纯文本类型的文件,整个配置文件是以区块的形式组织,通常每一个区块以一对大括号{}来 ...

  2. JavaScript map+parseInt 容易产生的误区

    map /** * 语法: * var new_array = arr.map(function callback(currentValue[,index[,array]]){ * // return ...

  3. Jsp内置对象application之统计浏览网页的次数

    <% Object obj = application.getAttribute("count"); if(obj !=null){ Integer sum = (Integ ...

  4. 解决SpringBoot页面跳转无法访问静态资源的问题

    初学SpringBoot,写项目的时候遇到了问题,原本的页面是这样的 但启动项目后是这样的 这是因为thymeleaf中引入静态资源及模板需要使用到 th:xxx 属性,否则无法在动态资源中访问静态资 ...

  5. N叉树的前后序遍历和最大深度

    package NTree; import java.util.ArrayList; import java.util.List; /** * N叉树的前后序遍历和最大深度 */ public cla ...

  6. fatal error: glib.h: No such file or directory

    在学习BLE bluez的时候,做了一个测试程序,看到gatttool.c下面有一个glib解析命令行的功能,想移植到自己的程序接口中,但是添加了#include <glib.h>后,出现 ...

  7. Jmeter 常用函数(11)- 详解 __TestPlanName

    如果你想查看更多 Jmeter 常用函数可以在这篇文章找找哦 https://www.cnblogs.com/poloyy/p/13291704.html 作用 返回测试计划名称 语法格式 ${__T ...

  8. Python3技巧:动态变量名

    Firstly 各位应该做过服务器运维吧,像这样: 那么,在服务器运维的程序中,最好的访问服务器的方式是:运维库名.服务器名 由于服务器名是动态的,所以变量名也是动态的.今天我们就来讲讲Python3 ...

  9. 2 Spark角色介绍及运行模式

    第2章 Spark角色介绍及运行模式 2.1 集群角色 从物理部署层面上来看,Spark主要分为两种类型的节点,Master节点和Worker节点:Master节点主要运行集群管理器的中心化部分,所承 ...

  10. Robot Framework(5)——自动化示例

    上篇介绍了一些selenium2在robot framework中的一些关键字,这一篇主要来记录一下实际应用 一.安装并导入Selenium2Library 安装的工作一开始已经完成,可以用pip l ...