客户端部分主要使用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服务器的更多相关文章

  1. IIS 下 搭建简单的FTP服务器

    1. 修改用户策略, 创建简单用户密码 命令行输入 gpedit.msc 打开组策略 位置 2. 创建一个FTP使用的用户 net user zhaobsh Test6530 /add 3. 安装II ...

  2. mongoDB介绍、安装、搭建简单的mongoDB服务器(一)

    相关网站 1. http://www.mongodb.org/ 官网,可以下载安装程序,和doc,和驱动等. 2. http://www.mongoing.com/ 国内官方网站,博客,问题谈论等  ...

  3. 转:【专题十二】实现一个简单的FTP服务器

    引言: 休息一个国庆节后好久没有更新文章了,主要是刚开始休息完心态还没有调整过来的, 现在差不多进入状态了, 所以继续和大家分享下网络编程的知识,在本专题中将和大家分享如何自己实现一个简单的FTP服务 ...

  4. 基于python2【重要】怎么自行搭建简单的web服务器

    基本流程:1.需要的支持     1)python本身有SimpleHTTPServer     2)ForkStaticServer.py支持,该文件放在python7目录下     3)将希望共享 ...

  5. 专题十二:实现一个简单的FTP服务器

    引言: 在本专题中将和大家分享如何自己实现一个简单的FTP服务器.在我们平时的上网过程中,一般都是使用FTP的客户端来对商家提供的服务器进行访问(上传.下载文件),例如我们经常用到微软的SkyDriv ...

  6. 搭建一个简单的FTP服务器

    本文介绍通过win7自带的IIS来搭建一个只能实现基本功能的FTP服务器,第一次装好WIN7后我愣是没整出来,后来查了一下网上资料经过试验后搭建成功,其实原理和步骤与windows前期的版本差不多,主 ...

  7. 使用 Nodejs 搭建简单的Web服务器

    使用Nodejs搭建Web服务器是学习Node.js比较全面的入门教程,因为要完成一个简单的Web服务器,你需要学习Nodejs中几个比较重要的模块,比如:http协议模块.文件系统.url解析模块. ...

  8. 用VLC Media Player搭建简单的流媒体服务器

    VLC可以作为播放器使用,也可以搭建服务器. 在经历了Helix Server和Darwin Streaming Server+Perl的失败之后,终于找到了一个搭建流媒体简单好用的方法. 这个网址中 ...

  9. Unity搭建简单的图片服务器

    具体要实现的目标是:将图片手动拷贝到服务器,然后在Unity中点击按钮将服务器中的图片加载到Unity中. 首先简答解释下 WAMP(Windows + Apache + Mysql + PHP),一 ...

随机推荐

  1. POJ3090 Visible Lattice Points

    /* * POJ3090 Visible Lattice Points * 欧拉函数 */ #include<cstdio> using namespace std; int C,N; / ...

  2. 3、zabbix配置入门

    Zabbix模板 zabbix组件:    zabbix-server    zabbix-database    zabbix-web    zabbix-agent    zabbix-proxy ...

  3. Java对象的访问方式

    之前写过一篇随笔 https://www.cnblogs.com/qianjinyan/p/10352749.html 现在看看,貌似不是很准确,方法区和栈应当区分开来,两者有很大的区别 看下面的一个 ...

  4. IOS 下载app

    ---------------------------------------------------------------------------------------------------- ...

  5. QGis+QT5.9+VS2017源码编译

    1.需要软件 VS2017 QT5.9.2 CMake 3.10.2 Cygwin osgeo4w QGIS源码 2.安装VS2017  过程省略 是由于机器上已经安装了VS2017 3.安装QT5. ...

  6. pipenv使用总结

    一.pipenv默认虚拟环境路径在用户目录下的.\virtualenvs下,不同虚拟环境目录不同,如果要更改为在当前项目根目录下,可以在项目根目录下手动创建.venv目录. 1.linux环境下设置环 ...

  7. Python *Mix_w

    Python的历史起源: 1989年圣诞节期间,由吉多.范罗苏姆创始. Python的优点"优美""明确""简单" python是一门解释型 ...

  8. [Leetcode 771]宝石和石子 Jewels and Stones HashSet简单应用

    [题目] You're given strings J representing the types of stones that are jewels, and S representing the ...

  9. SQL-44 将id=5以及emp_no=10001的行数据替换成id=5以及emp_no=10005,其他数据保持不变,使用replace实现。

    题目描述 将id=5以及emp_no=10001的行数据替换成id=5以及emp_no=10005,其他数据保持不变,使用replace实现.CREATE TABLE IF NOT EXISTS ti ...

  10. Android开发 ---SQLite数据库,lock文件,结果集游标,适配器,安全退出,给连接设置下划线,编辑器,投影,ContentValues存储,DbHelper,activity栈

    目录截图: 1.activity_main.xml 主界面效果: <?xml version="1.0" encoding="utf-8"?> &l ...