上传文件到服务器指定位置 & 从服务器指定位置下载文件
需要的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 文件上传和下载的实质:文件的拷贝 文件上传:从本地拷贝到服务器磁盘上 客户端需要编写文件上传表单---->服务端需要编 ...
随机推荐
- XCTF-WEB-新手练习区(5-8)笔记
5:disabled_button X老师今天上课讲了前端知识,然后给了大家一个不能按的按钮,小宁惊奇地发现这个按钮按不下去,到底怎么才能按下去呢? 删除disable="" 字段 ...
- C#LeetCode刷题-栈
栈篇 # 题名 刷题 通过率 难度 20 有效的括号 C#LeetCode刷题之#20-有效的括号(Valid Parentheses) 33.0% 简单 42 接雨水 35.6% 困难 71 简 ...
- JavaScript 中 Blob对象的初步认识
Blob Binary Large Object的缩写,二进制大对象 虽然在前端中开发并不常见,但是实际上MySql数据库中,可以通过设置一个Blob类型的数据来存储一个Blob对象的内容 语法 le ...
- C#图解教程(第四版)—01—类型,存储,变量
3.1 如何广泛的描述C#程序 可以说C程序是一组函数和数据类型,C++程序是一组函数和类,然而C#程序是一组类型声明 3.2 类型 可以把类型想象成一个用来创建数据结构的模板,模板本身并不是数据结构 ...
- 微信支付.NET SDK 中的BUG(存疑)
BUG出现在类文件WxPayData.cs中的FromXml(string xml)方法 /** * @将xml转为WxPayData对象并返回对象内部的数据 * @param string 待转换的 ...
- Oracle数据泵导出使用并行参数,单个表能否真正的并行?
对于Oracle 数据泵expdp,impdp是一种逻辑导出导入迁移数据的一个工具,是服务端的工具,常见于DBA人员使用,用于数据迁移.从A库迁移至B库,或者从A用户迁移至B用户等. 那么有个疑问? ...
- PythonCrashCourse 第二章习题
2.3 个性化消息:将用户的姓名存到一个变量中,并向该用户显示一条消息.显示的消息应非常简单,如"Hello Eric, would you like to learn some Pytho ...
- C++置换的玩笑
小蒜头又调皮了.这一次,姐姐的实验报告惨遭毒手. 姐姐的实验报告上原本记录着从 1 到 n 的序列,任意两个数字间用空格间隔.但是“坑姐”的蒜头居然把数字间的空格都给删掉了,整个数字序列变成一个长度为 ...
- 线程池之Executor框架
线程池之Executor框架 Java的线程既是工作单元,也是执行机制.从JDK5开始,把工作机单元和执行机制分离开来.工作单元包括Runnable和Callable,而执行机制由Executor框架 ...
- 瑞发科NS1081主控 + THGBM5G7A2JBAIR(eMMC) 制作16GB闪存驱动器
文档标识符:NS1081_FLASH-DRIVE_D-P9 作者:DLHC 最后修改日期:2020.8.22 本文链接:https://www.cnblogs.com/DLHC-TECH/p/NS10 ...