搭建简单的FTP服务器
客户端部分主要使用C#提供的webclient类 (https://msdn.microsoft.com/library/system.net.webclient.aspx)
通过WebClient.UploadData()方法进行提交。
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Title = "请选择文件";
fileDialog.Filter = "所有文件(*xls*)|*.xls*"; //设置要选择的文件的类型
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string file = fileDialog.FileName;//返回文件的完整路径
string url = "http://" + ClientSettings.Host + ":8087/upload?type=excel";
string filename = Path.GetFileName(file);
var wb = new WebClient(); var client = new HttpUpload(); string res = "";
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, , bytes.Length);
fs.Close();
client.SetFieldValue("uploadfile", filename, " application/octet-stream", bytes);
client.SetFieldValue("submit", "提交");
client.Upload(url, out res);
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Net; /// <summary>
/// 用于模拟POST上传文件到服务器
/// </summary>
public class HttpUpload
{
private ArrayList bytesArray;
private Encoding encoding = Encoding.UTF8;
private string boundary = String.Empty; public HttpUpload()
{
bytesArray = new ArrayList();
string flag = DateTime.Now.Ticks.ToString("x");
boundary = "---------------------------" + flag;
} /// <summary>
/// 合并请求数据
/// </summary>
/// <returns></returns>
private byte[] MergeContent()
{
int length = ;
int readLength = ;
string endBoundary = "--" + boundary + "--\r\n";
byte[] endBoundaryBytes = encoding.GetBytes(endBoundary); bytesArray.Add(endBoundaryBytes); foreach (byte[] b in bytesArray)
{
length += b.Length;
} byte[] bytes = new byte[length]; foreach (byte[] b in bytesArray)
{
b.CopyTo(bytes, readLength);
readLength += b.Length;
} return bytes;
} /// <summary>
/// 上传
/// </summary>
/// <param name="requestUrl">请求url</param>
/// <param name="responseText">响应</param>
/// <returns></returns>
public bool Upload(String requestUrl, out String responseText)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary); byte[] responseBytes;
byte[] bytes = MergeContent(); try
{
responseBytes = webClient.UploadData(requestUrl, "POST", bytes);
responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
return true;
}
catch (WebException ex)
{
Stream responseStream = ex.Response.GetResponseStream();
responseBytes = new byte[ex.Response.ContentLength];
responseStream.Read(responseBytes, , responseBytes.Length);
}
responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
return false;
} /// <summary>
/// 设置表单数据字段
/// </summary>
/// <param name="fieldName">字段名</param>
/// <param name="fieldValue">字段值</param>
/// <returns></returns>
public void SetFieldValue(String fieldName, String fieldValue)
{
string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
string httpRowData = String.Format(httpRow, fieldName, fieldValue); bytesArray.Add(encoding.GetBytes(httpRowData));
} /// <summary>
/// 设置表单文件数据
/// </summary>
/// <param name="fieldName">字段名</param>
/// <param name="filename">字段值</param>
/// <param name="contentType">内容内型</param>
/// <param name="fileBytes">文件字节流</param>
/// <returns></returns>
public void SetFieldValue(String fieldName, String filename, String contentType, Byte[] fileBytes)
{
string end = "\r\n";
string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string httpRowData = String.Format(httpRow, fieldName, filename, contentType); byte[] headerBytes = encoding.GetBytes(httpRowData);
byte[] endBytes = encoding.GetBytes(end);
byte[] fileDataBytes = new byte[headerBytes.Length + fileBytes.Length + endBytes.Length]; headerBytes.CopyTo(fileDataBytes, );
fileBytes.CopyTo(fileDataBytes, headerBytes.Length);
endBytes.CopyTo(fileDataBytes, headerBytes.Length + fileBytes.Length); bytesArray.Add(fileDataBytes);
}
}
服务器部分,搭建一个简单的web服务,接收POST请求即可.
下例是用GO写的一个简单的接收示例
func uploadHandler(res http.ResponseWriter, req *http.Request) {
switch req.Method {
case "POST":
{
ftype := req.FormValue("type")
if ftype == "excel" {
err := req.ParseMultipartForm()
if err != nil {
return
}
httpDoc := "/../../../Excels/"
m := req.MultipartForm
files := m.File["uploadfile"]
for i, _ := range files {
file, err := files[i].Open()
defer file.Close()
if err != nil {
return
}
tmp := strings.Split(files[i].Filename, "\\")
if len(tmp) <= {
tmp = strings.Split(files[i].Filename, "/")
if len(tmp) <= {
return
}
}
filename := tmp[len(tmp)-]
if filename == "" {
return
}
dst, err := os.Create(httpDoc + filename)
defer dst.Close()
if err != nil {
return
}
if _, err := io.Copy(dst, file); err != nil {
return
}
}
}
}
}
}
type PublishServer struct {
}
var serverm *PublishServer
func PublishServer_GetMe() *PublishServer {
if serverm == nil {
serverm = &PublishServer{}
serverm.Derived = serverm
}
return serverm
}
func (this *PublishServer) Init() bool {
// 启动http服务
StartHttpServer()
return true
}
func (this *PublishServer) MainLoop() {
time.Sleep(time.Millisecond * )
}
func StartHttpServer() {
// 读取JSON配置
httpProt := env.Get("publish", "httpport")
httpDoc := env.Get("publish", "httpdoc")
http.Handle("/", http.FileServer(http.Dir(httpDoc)))
http.Handle("/excels/", http.StripPrefix("/excels/", http.FileServer(http.Dir(httpDoc+"/../../../Excels/"))))
http.HandleFunc("/upload", uploadHandler)
go http.ListenAndServe(httpProt, nil)
}
Web页面
<html>
<body>
<h1> 上传页面 </h1>
<form name="uploadForm" method="POST"
enctype="multipart/form-data"
action="/upload?type=excel">
<b>Upload File:</b>
<br>
<input type="file" name="uploadfile" size=""/>
<br>
<input type="submit" name="submit" value="提交">
<input type="reset" name="reset" value="重置">
</form>
</body>
</html>
搭建简单的FTP服务器的更多相关文章
- IIS 下 搭建简单的FTP服务器
1. 修改用户策略, 创建简单用户密码 命令行输入 gpedit.msc 打开组策略 位置 2. 创建一个FTP使用的用户 net user zhaobsh Test6530 /add 3. 安装II ...
- mongoDB介绍、安装、搭建简单的mongoDB服务器(一)
相关网站 1. http://www.mongodb.org/ 官网,可以下载安装程序,和doc,和驱动等. 2. http://www.mongoing.com/ 国内官方网站,博客,问题谈论等 ...
- 转:【专题十二】实现一个简单的FTP服务器
引言: 休息一个国庆节后好久没有更新文章了,主要是刚开始休息完心态还没有调整过来的, 现在差不多进入状态了, 所以继续和大家分享下网络编程的知识,在本专题中将和大家分享如何自己实现一个简单的FTP服务 ...
- 基于python2【重要】怎么自行搭建简单的web服务器
基本流程:1.需要的支持 1)python本身有SimpleHTTPServer 2)ForkStaticServer.py支持,该文件放在python7目录下 3)将希望共享 ...
- 专题十二:实现一个简单的FTP服务器
引言: 在本专题中将和大家分享如何自己实现一个简单的FTP服务器.在我们平时的上网过程中,一般都是使用FTP的客户端来对商家提供的服务器进行访问(上传.下载文件),例如我们经常用到微软的SkyDriv ...
- 搭建一个简单的FTP服务器
本文介绍通过win7自带的IIS来搭建一个只能实现基本功能的FTP服务器,第一次装好WIN7后我愣是没整出来,后来查了一下网上资料经过试验后搭建成功,其实原理和步骤与windows前期的版本差不多,主 ...
- 使用 Nodejs 搭建简单的Web服务器
使用Nodejs搭建Web服务器是学习Node.js比较全面的入门教程,因为要完成一个简单的Web服务器,你需要学习Nodejs中几个比较重要的模块,比如:http协议模块.文件系统.url解析模块. ...
- 用VLC Media Player搭建简单的流媒体服务器
VLC可以作为播放器使用,也可以搭建服务器. 在经历了Helix Server和Darwin Streaming Server+Perl的失败之后,终于找到了一个搭建流媒体简单好用的方法. 这个网址中 ...
- Unity搭建简单的图片服务器
具体要实现的目标是:将图片手动拷贝到服务器,然后在Unity中点击按钮将服务器中的图片加载到Unity中. 首先简答解释下 WAMP(Windows + Apache + Mysql + PHP),一 ...
随机推荐
- 掌握闭包closure (含义及优缺点)
个人认为闭包其实非常好理解,我们一起去认识什么是闭包. 在javascript脚本语言中,变量的作用域只有两种,一种是全局变量,一种是局部变量. 全局变量的函数可以在整个javascript脚本语言中 ...
- centos 打印机安装方法
这里安装的是hplip 1.首先确定cups有没有安装 没有的话 yum install cups 安装 2.安装 hplip yum install -y hplip hplip-* 3执行 hp- ...
- spring cloud 版本号与 boot版本之间的对应关系(版本不对,会导致pom无法引入)
版本号规则 Spring Cloud并没有熟悉的数字版本号,而是对应一个开发代号. 开发代号看似没有什么规律,但实际上首字母是有顺序的,比如:Dalston版本,我们可以简称 D 版本,对应的 Edg ...
- ES6之Array数组
定义数组 ,]; const arr = new Array(1,2,3,4); const array1 = new Array(); array1[]="test"; 给数组不 ...
- "她等待刀尖已经太久"--茨维塔耶娃诗抄
生活 1 你无法夺走我的红晕—— 它强大——如同河水的汛潮! 你是猎人,可我不会上当, 你若追逐,我就会逃跑. 你无法夺走我鲜活的灵魂! 就这样,在急遽的追逐中—— 一匹阿拉伯的骏马, 微 ...
- Alpha阶段敏捷冲刺
博客连链接集合 第一篇:http://www.cnblogs.com/just-let-it-go/p/8875433.html 第二篇:http://www.cnblogs.com/just-let ...
- 使用cookie记录页面跳转次数,然后从最后一级页面跳转回首页面
1.首先,给出cookie设置,获取,删除的操作函数. function setCookie(name,value) { var Days = 30; var ex ...
- 2010-10-08在浏览器中兼容+jQuery3
一.实现背景图片铺满(兼容各种浏览器) <script type="text/javascript"> $(document).ready(function() { $ ...
- python - 基础知识,if语句
一.认识计算机 计算机是一个高度集成的电子电路. 组成:CPU(中央处理器).内存 .主板 .电源(心脏) .显示器 .键盘 .鼠标 .显卡(NAVID,AMD) .硬盘 操作系统 :Windo ...
- Java线程池ThreadPoolExecutor&&Executors
一.先看看传统的开启线程. new Thread(new Runnable() { @Override public void run() { } }).start(); 缺点: 1.每次new Th ...