Fivee

导航

搭建简单的FTP服务器

客户端部分主要使用C#提供的webclient类 (https://msdn.microsoft.com/library/system.net.webclient.aspx)

通过WebClient.UploadData()方法进行提交。

 1 OpenFileDialog fileDialog = new OpenFileDialog();
 2 fileDialog.Multiselect = true;
 3 fileDialog.Title = "请选择文件";
 4 fileDialog.Filter = "所有文件(*xls*)|*.xls*"; //设置要选择的文件的类型
 5 if (fileDialog.ShowDialog() == DialogResult.OK)
 6 {
 7     string file = fileDialog.FileName;//返回文件的完整路径        
 8     string url = "http://" + ClientSettings.Host + ":8087/upload?type=excel";
 9     string filename = Path.GetFileName(file);
10     var wb = new WebClient();
11 
12     var client = new HttpUpload();
13 
14     string res = "";
15     FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
16     byte[] bytes = new byte[(int)fs.Length];
17     fs.Read(bytes, 0, bytes.Length);
18     fs.Close();
19     client.SetFieldValue("uploadfile", filename, " application/octet-stream", bytes);
20     client.SetFieldValue("submit", "提交");
21     client.Upload(url, out res);
22 }        
View Code
  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using System.Linq;
  5 using System.IO;
  6 using System.Text;
  7 using System.Net;
  8 
  9 /// <summary>
 10 /// 用于模拟POST上传文件到服务器
 11 /// </summary>
 12 public class HttpUpload
 13 {
 14     private ArrayList bytesArray;
 15     private Encoding encoding = Encoding.UTF8;
 16     private string boundary = String.Empty;
 17 
 18     public HttpUpload()
 19     {
 20         bytesArray = new ArrayList();
 21         string flag = DateTime.Now.Ticks.ToString("x");
 22         boundary = "---------------------------" + flag;
 23     }
 24 
 25     /// <summary>
 26     /// 合并请求数据
 27     /// </summary>
 28     /// <returns></returns>
 29     private byte[] MergeContent()
 30     {
 31         int length = 0;
 32         int readLength = 0;
 33         string endBoundary = "--" + boundary + "--\r\n";
 34         byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);
 35 
 36         bytesArray.Add(endBoundaryBytes);
 37 
 38         foreach (byte[] b in bytesArray)
 39         {
 40             length += b.Length;
 41         }
 42 
 43         byte[] bytes = new byte[length];
 44 
 45         foreach (byte[] b in bytesArray)
 46         {
 47             b.CopyTo(bytes, readLength);
 48             readLength += b.Length;
 49         }
 50 
 51         return bytes;
 52     }
 53 
 54     /// <summary>
 55     /// 上传
 56     /// </summary>
 57     /// <param name="requestUrl">请求url</param>
 58     /// <param name="responseText">响应</param>
 59     /// <returns></returns>
 60     public bool Upload(String requestUrl, out String responseText)
 61     {
 62         WebClient webClient = new WebClient();
 63         webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
 64 
 65         byte[] responseBytes;
 66         byte[] bytes = MergeContent();
 67 
 68         try
 69         {
 70             responseBytes = webClient.UploadData(requestUrl, "POST", bytes);
 71             responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
 72             return true;
 73         }
 74         catch (WebException ex)
 75         {
 76             Stream responseStream = ex.Response.GetResponseStream();
 77             responseBytes = new byte[ex.Response.ContentLength];
 78             responseStream.Read(responseBytes, 0, responseBytes.Length);
 79         }
 80         responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
 81         return false;
 82     }
 83 
 84     /// <summary>
 85     /// 设置表单数据字段
 86     /// </summary>
 87     /// <param name="fieldName">字段名</param>
 88     /// <param name="fieldValue">字段值</param>
 89     /// <returns></returns>
 90     public void SetFieldValue(String fieldName, String fieldValue)
 91     {
 92         string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
 93         string httpRowData = String.Format(httpRow, fieldName, fieldValue);
 94 
 95         bytesArray.Add(encoding.GetBytes(httpRowData));
 96     }
 97 
 98     /// <summary>
 99     /// 设置表单文件数据
100     /// </summary>
101     /// <param name="fieldName">字段名</param>
102     /// <param name="filename">字段值</param>
103     /// <param name="contentType">内容内型</param>
104     /// <param name="fileBytes">文件字节流</param>
105     /// <returns></returns>
106     public void SetFieldValue(String fieldName, String filename, String contentType, Byte[] fileBytes)
107     {
108         string end = "\r\n";
109         string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
110         string httpRowData = String.Format(httpRow, fieldName, filename, contentType);
111 
112         byte[] headerBytes = encoding.GetBytes(httpRowData);
113         byte[] endBytes = encoding.GetBytes(end);
114         byte[] fileDataBytes = new byte[headerBytes.Length + fileBytes.Length + endBytes.Length];
115 
116         headerBytes.CopyTo(fileDataBytes, 0);
117         fileBytes.CopyTo(fileDataBytes, headerBytes.Length);
118         endBytes.CopyTo(fileDataBytes, headerBytes.Length + fileBytes.Length);
119 
120         bytesArray.Add(fileDataBytes);
121     }
122 }
View Code

服务器部分,搭建一个简单的web服务,接收POST请求即可.

下例是用GO写的一个简单的接收示例

 1 func uploadHandler(res http.ResponseWriter, req *http.Request) {
 2     switch req.Method {
 3     case "POST":
 4         {
 5             ftype := req.FormValue("type")
 6             if ftype == "excel" {
 7                 err := req.ParseMultipartForm(100000)
 8                 if err != nil {
 9                     return
10                 }
11 
12                 httpDoc := "/../../../Excels/"
13                 m := req.MultipartForm
14 
15                 files := m.File["uploadfile"]
16                 for i, _ := range files {
17                     file, err := files[i].Open()
18                     defer file.Close()
19                     if err != nil {
20                         return
21                     }
22 
23                     tmp := strings.Split(files[i].Filename, "\\")
24                     if len(tmp) <= 0 {
25                         tmp = strings.Split(files[i].Filename, "/")
26                         if len(tmp) <= 0 {
27                             return
28                         }
29                     }
30 
31                     filename := tmp[len(tmp)-1]
32                     if filename == "" {
33                         return
34                     }
35 
36                     dst, err := os.Create(httpDoc + filename)
37                     defer dst.Close()
38                     if err != nil {
39                         return
40                     }
41 
42                     if _, err := io.Copy(dst, file); err != nil {
43                         return
44                     }
45                 }
46             }
47         }
48     }
49 }
50 
51 type PublishServer struct {
52     
53 }
54 var serverm *PublishServer
55 
56 func PublishServer_GetMe() *PublishServer {
57     if serverm == nil {
58         serverm = &PublishServer{}
59         serverm.Derived = serverm
60     }
61     return serverm
62 }
63 
64 func (this *PublishServer) Init() bool {
65     // 启动http服务
66     StartHttpServer()
67 
68     return true
69 }
70 
71 func (this *PublishServer) MainLoop() {
72     time.Sleep(time.Millisecond * 50)
73 }
74 
75 func StartHttpServer() {
76     // 读取JSON配置
77     httpProt := env.Get("publish", "httpport")
78     httpDoc := env.Get("publish", "httpdoc")
79 
80     http.Handle("/", http.FileServer(http.Dir(httpDoc)))
81     http.Handle("/excels/", http.StripPrefix("/excels/", http.FileServer(http.Dir(httpDoc+"/../../../Excels/"))))
82     http.HandleFunc("/upload", uploadHandler)
83 
84     go http.ListenAndServe(httpProt, nil)
85 }
View Code

Web页面

 1 <html>
 2   <body>
 3     <h1> 上传页面 </h1>
 4     <form name="uploadForm" method="POST"
 5           enctype="multipart/form-data"
 6           action="/upload?type=excel">
 7       <b>Upload File:</b>
 8       <br>
 9       <input type="file" name="uploadfile" size="64"/>
10       <br>
11       <input type="submit" name="submit" value="提交">
12       <input type="reset" name="reset" value="重置">
13     </form>
14   </body>
15 </html>
View Code

 

posted on 2018-04-18 17:34  Fivee  阅读(362)  评论(0)    收藏  举报