客户端部分主要使用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. ssm回顾笔记(一)

    这两天来到了农银,这边即将进行的一个项目是将ssh框架的电商项目迁移到springboot+ssm框架上,所以我基本上是三门技术在同时进行学习,当然以前学过ssm,现在只是回顾. spring 注解 ...

  2. Linux——命令

    1.pod2text    # 功能输出处理对象(脚本)中的的=head1 ...=head1 ......=cut框架中的信息 2.date           # 输出时间  eg: Sat Ju ...

  3. Lintcode105 Copy List with Random Pointer solution 题解

    [题目描述] A linked list is given such that each node contains an additional random pointer which could ...

  4. maven 如何使用

    以前没有用过maven管理过项目的依赖,最后使用上了maven,发现通过不能方式建立出来的web应用程序目录结构基本都不一样,既然每次都要到网上搜索如何建立maven管理的Web应用程序,不如自己找百 ...

  5. DP入门水题集

    HDU 1087 Input contains multiple test cases. Each test case is described in a line as follow:N value ...

  6. JxBrowser之三:常用函数setNetworkDelegate

    1.常用函数setNetworkDelegate,包含对网络传输数据状态的多种监控回调. 2.着重说一下其中的几个函数 BrowserContext browserContext = BrowserC ...

  7. spring-mvc默认首页配置

    一想到默认首页,很多人可能首先想到的是在web.xml如下配置: <welcome-file-list> <welcome-file>xxxx/xxx</welcome- ...

  8. C# Log4Net 日志

    C#使用Log4Net记录日志 第一步:下载Log4Net            下载地址:http://logging.apache.org/log4net/download_log4net.cgi ...

  9. Rails6.0 Beta版本1: Action Text的简单使用

    主要功能是新增2个主要的框架Mailbox和action Text. 和2个重要的可扩展的升级: multiple databases support和parallel testing. Action ...

  10. 精确率、准确率、召回率和F1值

    当我们训练一个分类模型,总要有一些指标来衡量这个模型的优劣.一般可以用如题的指标来对预测数据做评估,同时对模型进行评估. 首先先理解一下混淆矩阵,混淆矩阵也称误差矩阵,是表示精度评价的一种标准格式,用 ...