搭建简单的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),一 ...
随机推荐
- JsonWebToken Demo(转)
namespace TokenTest { using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System. ...
- vue--实例化对象
根目录下的文件,这些是创建vue项目时生成的配置文件 node_modules=> 里面的文件是项目开发过种中的各种依赖,我们暂且不用去深入了解: public=> 主要放的是一些公用的文 ...
- Jade入门学习笔记
jade是超高性能的node JavaScript模板引擎,有着非常强大的API和大量杰出的特性.它主要针对node的服务端.由于商标的原因,改为Pug,哈巴狗.Pug有它本身的缺点--可移植性差,调 ...
- Mac redis安装
Download, extract and compile Redis with: #进入下载目录 $ cd ... $ wget http://download.redis.io/releases/ ...
- Java使用Sockt进行通信(2)
使用TCP协议编写Sockt TCP(Transmission Control Protocol 传输控制协议)是一种面向连接的.可靠的.基于字节流的传输层通信协议,由IETF的RFC 793定义. ...
- npm init 命令生成package.json文件
通过npm init 命令可以生成一个package.json文件.这个文件是 整个项目的描述文件.通过这个文件可以清楚的知道项目的包依赖关系,版本,作者等信息.每个NPM包都有自己的package. ...
- Dynamic networks | 动态网络
Dynamic networks reveal key players in aging 系统生物学中的网络分析 网络的拓扑结构:topological properties, 网络的度:whole ...
- php 截取 小程序上传到服务器图片,
截取字符串传入数据库 $f_slide = htmlspecialchars_decode($_REQUEST['f_slide']); // echo "<pre>" ...
- 高并发情况下Linux系统及kernel参数优化
众所周知在默认参数情况下Linux对高并发支持并不好,主要受限于单进程最大打开文件数限制.内核TCP参数方面和IO事件分配机制等.下面就从几方面来调整使Linux系统能够支持高并发环境. Iptabl ...
- react-thunk的使用流程
react-thunk作用:使我们可以在action中返回函数,而不是只能返回一个对象.然后我们可以在函数中做很多事情,比如发送异步的ajax请求. 这就是react-thunk的使用方法.接受一个d ...