上传文件到服务器指定位置 & 从服务器指定位置下载文件
需要的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();
}
}
}
} }
点击查看
上传文件到服务器指定位置 & 从服务器指定位置下载文件的更多相关文章
- spring mvc 图片上传,图片压缩、跨域解决、 按天生成文件夹 ,删除,限制为图片代码等相关配置
spring mvc 图片上传,跨域解决 按天生成文件夹 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ ...
- Web---文件上传-用apache的工具处理、打散目录、简单文件上传进度
我们需要先准备好2个apache的类: 上一个博客文章只讲了最简单的入门,现在来开始慢慢加深. 先过渡一下:只上传一个file项 index.jsp: <h2>用apache的工具处理文件 ...
- 使用递归方法实现,向FTP服务器上传整个目录结构、从FTP服务器下载整个目录到本地的功能
我最近由于在做一个关于FTP文件上传和下载的功能时候,发现Apache FTP jar包没有提供对整个目录结构的上传和下载功能,只能非目录类型的文件进行上传和下载操作,后来我查阅很多网上的实现方法,再 ...
- kindeditor修改图片上传路径-使用webapi上传图片到图片服务器
kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 在这里我着重介绍一些使用kindeditor修改图片上传路径并通过webapi上传图片到图片服务器的方案. 因为我使用的 ...
- 码云git使用一(上传本地项目到码云git服务器上)
主要讲下如果将项目部署到码云git服务器上,然后使用studio导入git项目,修改本地代码后,并同步到码云git上面. 首先:我们在码云上注册账号并登陆.官网(https://git.oschina ...
- C# HTTP系列12 以form-data方式上传键值对集合到远程服务器
系列目录 [已更新最新开发文章,点击查看详细] 使用multipart/form-data方式提交数据与普通的post方式有一定区别.multipart/form-data的请求头必须包含一个 ...
- PHP使用文件流下载文件方法(附:解决下载文件内容乱码问题)
1.flush - 刷新输出缓冲 2.ob_clean - 清空(擦掉)输出缓冲区 此函数用来丢弃输出缓冲区中的内容. 此函数不会销毁输出缓冲区,而像 ob_end_clean() 函数会销毁输出缓冲 ...
- vue+element-ui upload图片上传前大小超过4m,自动压缩到指定大小,长宽
最近项目需要实现一个需求,用户上传图片时,图片大小超过4M,长宽超过2000,需要压缩到400k,2000宽高.在git上找到一个不错的方法,把实现方法总结一下: 安装image-conversion ...
- linux学习 XShell上传、下载本地文件到linux服务器
(一)通过命令行的方式 1.linux服务器端设置 在linux主机上,安装上传下载工具包rz及sz; 如果不知道你要安装包的具体名称,可以使用yum provides */name 进行查找系统自带 ...
- 【JAVAWEB学习笔记】29_文件的上传------commons-fileupload
今天内容: 文件的上传------commons-fileupload 文件上传和下载的实质:文件的拷贝 文件上传:从本地拷贝到服务器磁盘上 客户端需要编写文件上传表单---->服务端需要编 ...
随机推荐
- Vue组件通信之子传父
子组件向父组件通信主要通过自定义事件实现. 这里我记录一个小例子来帮助自己记忆. 通过点击子组件的按钮去执行父组件的函数并使用子组件传来的数据. 子组件定义如下: <template id=&q ...
- effectivejava(破坏单例)
以下代码是最普通的双重锁的单例实现形式 package com.edu.character02; import java.io.Serializable; /** * <p> * 双重锁 ...
- odoo12 Tree视图创建编辑旁边新增按钮,并根据条件隐藏
前言 我们通常在form视图中可以很简单地在header里面添加按钮,但是在某些情况下,我们也需要在Tree视图中添加按钮,但是odoo官方目前没有给我们提供相应的接口,因此,我们尝试自己来实现它.最 ...
- Golang 简单爬虫实现,爬取小说
为什么要使用Go写爬虫呢? 对于我而言,这仅仅是练习Golang的一种方式. 所以,我没有使用爬虫框架,虽然其很高效. 为什么我要写这篇文章? 将我在写爬虫时找到资料做一个总结,希望对于想使用Gola ...
- 金题大战Vol.0 C、树上的等差数列
金题大战Vol.0 C.树上的等差数列 题目描述 给定一棵包含\(N\)个节点的无根树,节点编号\(1-N\).其中每个节点都具有一个权值,第\(i\)个节点的权值是\(A_i\). 小\(Hi\)希 ...
- Qt信号与槽使用方法最完整总结
在图形界面编程中(参考<C++最好的图形库是什么?>),组件之间如何实现通信是核心的技术内容.Qt 使用了信号与槽的机制,非常的高效.简单.易学,方便开发者的使用.本文详细的介绍了Qt 当 ...
- Mysql Lost connection to MySQL server at ‘reading initial communication packet', system error: 0
在用Navicat for MySQL远程连接mysql的时候,出现了 Lost connection to MySQL server at ‘reading initial communicatio ...
- 基于函数的I/O操作(头文件stdio.h)
基于函数库的I/O是C语言标准库的功能,基于系统级I/O函数实现. 系统级I/O函数对文件的标识是文件描述符,C语言标准库中对文件的标识是指向FILE结构的指针.在头文件cstdio或stdio.h中 ...
- 第五篇 Scrum冲刺博客
一.会议图片 二.项目进展 成员 完成情况 今日任务 冯荣新 未完成 购物车列表,购物车工具栏 陈泽佳 未完成 静态结构 徐伟浩 商品信息录入 协助前端获取数据 谢佳余 未完成 搜索算法设计 邓帆涛 ...
- python字典的概念与基本操作
字典是非常常用的一种数据结构,它与json格式的数据非常相似,核心就是以键值对的形式存储数据,关于Python中的字典做如下四点说明: 1.构造字典对象需要用大括号表示 {},每个字典元素都是以键值对 ...