上传文件到服务器指定位置 & 从服务器指定位置下载文件
需要的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 文件上传和下载的实质:文件的拷贝 文件上传:从本地拷贝到服务器磁盘上 客户端需要编写文件上传表单---->服务端需要编 ...
随机推荐
- C#-用Winform制作一个简单的密码管理工具
为什么要做? 首先是为了练习一下c#. 想必大家都有过记不起某个平台的账号密码的经历,那种感受着实令人抓狂.那这么多账号密码根本记不住!我之前用python写过一个超级简单(连账号信息都写在代码里那种 ...
- Setup Factory 9 打包安装程序过程中提示安装.net4.5、并启用md5加密算法
1.在Before Installing选项卡中选择Ready to Install,点击Edit进入编辑窗口,切到最后一个选项卡Actions,把判断内容复制进去 -- These actions ...
- LeetCode 646 最长数对链详解
题目描述 给出 n 个数对. 在每一个数对中,第一个数字总是比第二个数字小. 现在,我们定义一种跟随关系,当且仅当 b < c 时,数对(c, d) 才可以跟在 (a, b) 后面.我们用这种形 ...
- 一个简单的RPC框架实现
package com.rpc; public interface EchoService { String echo(String ping); } package com.rpc; public ...
- js截取URL网址参数
将本页代码复制粘贴到html页面,打开即可. <!DOCTYPE html> <html lang="en"> <head> <meta ...
- vue watch 和 computed 区别与使用
目录 computed 和 watch 的说明 与 区别 computed 计算属性说明: watch 监听属性说明: watch 和 computed 的区别是: 使用 参考官方文档 compute ...
- 深入源码理解Spark RDD的数据分区原理
通过内存创建RDD的分区设置 1.示例代码 在创建RDD的时候,我们可以从内存中进行创建:输出保存为文件.为了演示效果,我们的示例代码如下: import org.apache.spark.{Spar ...
- JavaScript学习系列博客_24_JavaScript 原型对象
原型(prototype) - 创建一个函数(所有函数)以后,解析器都会默认在函数中添加一个属性prototype prototype属性指向的是一个对象,这个对象我们称为原型对象. 创建一个函数My ...
- 企业项目实战 .Net Core + Vue/Angular 分库分表日志系统四 | 强化设计方案
教程预览 01 | 前言 02 | 简单的分库分表设计 03 | 控制反转搭配简单业务 04 | 强化设计方案 强化 先来记录一下我们现在的样子,一会好做个对比 1.在EasyLogger.DbSto ...
- MySQL数据库根据一个或多个字段查询重复数据
系统在开发测试过程中出现bug,比如并发操作没有处理好,数据库中往往会插入重复数据,这些脏数据经常会导致各种问题.bug可以修改,但是数据往往也要处理,处理SQL如下: 1.根据一个字段查找重复数据 ...