需要的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. SonarQube 扫描 Java 代码

    SonarQube 扫描 Java 代码 环境 需要提前安装好 SonarQube7.9,安装步骤见 Docker 安装 SonarQube 步骤 填写项目名 my_project 填写token名 ...

  2. ECharts 常见的问题总结

    以前也用过ECharts(不得不说,这真的是百度的良心产品),但是都是一些简单的示例.这次因为工作的需要,做了很多表格,对ECharts有了更加深刻的理解,现在来总结一下. 第一个肯定是新手经常遇到的 ...

  3. for循环的插入元素

    Scanner input = new Scanner(System.in);  int[] num = new int[5];  for (int i = 0; i < num.length; ...

  4. 【SDOI2009】 HH的项链 - 莫队

    题目描述 HH 有一串由各种漂亮的贝壳组成的项链.HH 相信不同的贝壳会带来好运,所以每次散步完后,他都会随意取出一段贝壳,思考它们所表达的含义.HH 不断地收集新的贝壳,因此,他的项链变得越来越长. ...

  5. Linux top详解

    命令 top 参数说明: d:改变显示的更新速度 q:  没有任何延迟的显示速度 c:切换显示模式,共有两种模式,一是只显示执行档的名称,零一种显示完整的路径与名称S:累计模式,会将已完成或消失的子行 ...

  6. Java并发编程(07):Fork/Join框架机制详解

    本文源码:GitHub·点这里 || GitEE·点这里 一.Fork/Join框架 Java提供Fork/Join框架用于并行执行任务,核心的思想就是将一个大任务切分成多个小任务,然后汇总每个小任务 ...

  7. 手把手教你写VueRouter

    Vue-Router提供了俩个组件 `router-link` `router-view`, 提供了俩个原型上的属性`$route` `$router` ,我现在跟着源码来把它实现一下 开始 先看平时 ...

  8. 根据appid跳到App Store某个APP的详情页

    需求 本手机是否装了某个APP 示例百度appid 382201985  scheme BaiduSSO:// 1.是,直接打开百度APP 2.否,跳到App Store百度APP的详情页 NSStr ...

  9. HDFS 2.X新特性

    1 集群间数据拷贝 1.scp实现两个远程主机之间的文件复制 scp -r hello.txt root@hadoop103:/user/atguigu/hello.txt // 推 push scp ...

  10. python编程中的并发------多线程threading模块

    任务例子:喝水.吃饭动作需要耗时1S 单任务:(耗时20s) for i in range(10): print('a正在喝水') time.sleep(1) print('a正在吃饭') time. ...