c# http协议上传文件+传输数数据

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleApplication2.selectSDF.http
{
    class Uploadzip
    {
        static void Main(string[] args) {
            string Upload_Url = "http://device.js.cn/rest?method=zh,grabbinglog";
            int timeOut = 30000;
            string ZipedFile= "D:/Project/启动文件.jpg";

            Dictionary<string, string> myCol = new Dictionary<string, string>();
            myCol.Add("00000000", "xxxxxxxx");
            myCol.Add("commandId", "xxxxx");
            myCol.Add("deviceSn",  "xxxxxxxx");

            //文件地址,响应时间,file,文件路径,传输数据
            HttpPostData(Upload_Url, timeOut, "file", ZipedFile, myCol);             
        }

        /// <summary>
        ///   文件上传及数据传输
        /// </summary>
        /// <param name="url"> 访问的服务器地址及接口</param>
        /// <param name="timeOut">设置请求超时时间</param>
        /// <param name="fileKeyName">file</param>
        /// <param name="filePath">文件上传的本地路径</param>
        /// <param name="list">传输的json数据</param>
        /// <returns></returns>
        public static string HttpPostData(string url, int timeOut, string fileKeyName, string filePath, Dictionary<string, string> list) 
        {
            string responseContent;
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            // 设置属性
            webRequest.Method = "POST";
            webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            // 写入文件----------1.--------------
            string filename = filePath.Substring(filePath.LastIndexOf("/")+ 1);
             string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=" + filename + "\r\n" + "Content-Type: application/octet-stream\r\n\r\n";                 
            var header = string.Format(filePartHeader, fileKeyName, filePath);

            var headerbytes = Encoding.UTF8.GetBytes(header);
            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            var buffer = new byte[1024];
            int bytesRead; // =0

            while((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }
 
            string stringKeyHeader = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";     
            foreach (var item in list)
            {   //----------- 传输数据的编码集。
                var dataByte = Encoding.UTF8.GetBytes(string.Format(stringKeyHeader, item.Key, item.Value));
                memStream.Write(dataByte, 0, dataByte.Length);//循环写入 参数  
            }             

            // 写入最后的结束边界符------------ 3.-------------------------
            memStream.Write(endBoundary, 0, endBoundary.Length);

            webRequest.ContentLength = memStream.Length;

            var requestStream = webRequest.GetRequestStream();

            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();

            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

            //响应 ------------------- 4.-----------------------------------
            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")) )
            {
                responseContent = httpStreamReader.ReadToEnd();
            }

            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            return responseContent;
        }
    }

}



  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
C#窗体客户端可以使用网络编程中的FTP(文件传输协议)或HTTP(超文本传输协议)协议来实现上传下载文件。下面分别介绍两种方式: 1. 使用FTP协议上传下载文件 FTP协议是一种常用的文件传输协议,C#中可以使用FtpWebRequest类实现FTP文件上传下载。具体步骤如下: 上传文件: 1. 创建一个FtpWebRequest对象,指定FTP服务器地址、用户名和密码,并设置FTP命令为上传文件。 2. 使用FtpWebRequest对象的GetRequestStream方法获取上传流。 3. 将要上传的文件读取到内存流中。 4. 将内存流中的数据写入上传流中。 5. 关闭上传流。 下载文件: 1. 创建一个FtpWebRequest对象,指定FTP服务器地址、用户名和密码,并设置FTP命令为下载文件。 2. 使用FtpWebRequest对象的GetResponse方法获取下载响应。 3. 使用下载响应的GetResponseStream方法获取下载流。 4. 将下载流中的数据读取到本地文件中。 5. 关闭下载流。 下面是一个简单的示例代码: ```csharp using System; using System.IO; using System.Net; namespace Client { class Program { static void Main(string[] args) { // 上传文件 string ftpServer = "FTP服务器地址"; string userName = "FTP用户名"; string password = "FTP密码"; string localFilePath = "本地文件路径"; string remoteFilePath = "服务器文件路径"; FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpServer + remoteFilePath)); ftpRequest.Credentials = new NetworkCredential(userName, password); ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; using (FileStream fs = File.OpenRead(localFilePath)) using (Stream ftpStream = ftpRequest.GetRequestStream()) { byte[] buffer = new byte[1024]; int bytesRead = 0; do { bytesRead = fs.Read(buffer, 0, buffer.Length); ftpStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); Console.WriteLine("文件上传成功!"); } // 下载文件 string localFolderPath = "本地文件夹路径"; string remoteFileName = "服务器文件名"; ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpServer + remoteFileName)); ftpRequest.Credentials = new NetworkCredential(userName, password); ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; using (WebResponse response = ftpRequest.GetResponse()) using (Stream ftpStream = response.GetResponseStream()) using (FileStream fs = new FileStream(localFolderPath + "\\" + remoteFileName, FileMode.Create)) { byte[] buffer = new byte[1024]; int bytesRead = 0; do { bytesRead = ftpStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, bytesRead); } while (bytesRead > 0); Console.WriteLine("文件下载成功!"); } Console.ReadKey(); } } } ``` 2. 使用HTTP协议上传下载文件 HTTP协议是一种常用的超文本传输协议,C#中可以使用HttpClient类实现HTTP文件上传下载。具体步骤如下: 上传文件: 1. 创建一个HttpClient对象。 2. 使用HttpClient对象的PostAsync方法上传文件。 3. 将要上传的文件读取到内存流中。 4. 将内存流中的数据写入上传流中。 5. 关闭上传流。 下载文件: 1. 创建一个HttpClient对象。 2. 使用HttpClient对象的GetAsync方法下载文件。 3. 使用下载响应的Content属性获取下载流。 4. 将下载流中的数据读取到本地文件中。 5. 关闭下载流。 下面是一个简单的示例代码: ```csharp using System; using System.IO; using System.Net.Http; namespace Client { class Program { static async Task Main(string[] args) { // 上传文件 string serverUrl = "服务器地址"; string localFilePath = "本地文件路径"; string remoteFilePath = "服务器文件路径"; using (HttpClient httpClient = new HttpClient()) using (FileStream fs = new FileStream(localFilePath, FileMode.Open, FileAccess.Read)) using (StreamContent streamContent = new StreamContent(fs)) using (HttpResponseMessage response = await httpClient.PostAsync(serverUrl + remoteFilePath, streamContent)) { Console.WriteLine("文件上传成功!"); } // 下载文件 string localFolderPath = "本地文件夹路径"; string remoteFileName = "服务器文件名"; using (HttpClient httpClient = new HttpClient()) using (HttpResponseMessage response = await httpClient.GetAsync(serverUrl + remoteFileName)) using (Stream stream = await response.Content.ReadAsStreamAsync()) using (FileStream fs = new FileStream(localFolderPath + "\\" + remoteFileName, FileMode.Create)) { byte[] buffer = new byte[1024]; int bytesRead = 0; do { bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); await fs.WriteAsync(buffer, 0, bytesRead); } while (bytesRead > 0); Console.WriteLine("文件下载成功!"); } Console.ReadKey(); } } } ``` 注意:在实际开发中,需要根据具体需求进行上传下载文件的协议设计和错误处理等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值