溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

上傳文件到服務(wù)器端_C#

發(fā)布時間:2020-08-08 16:47:39 來源:ITPUB博客 閱讀:160 作者:tjxy9rjxl3QP 欄目:建站服務(wù)器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net;
using System.IO;

namespace www.xinduofen.cn
{
    /// <summary>
    /// C#與http服務(wù)器端進(jìn)行對接的工具類
    /// </summary>
    class www.xinduofen.com
    {
        /// <summary>
        /// 用于緩存服務(wù)器端傳輸?shù)娇蛻舳说腟ESSIONID或者JSESSIONID
        /// </summary>
        private Cookie sessionidCookie = null;
        
        /// <summary>
        /// 向HttpWebServer端上傳文件(使用的是"post"方式)
        /// </summary>
        /// <param name="url">請求網(wǎng)址</param>
        /// <param name="data">請求參數(shù)集合,無需參數(shù)時傳入null值</param>
        /// <param name="cookies">請求cookie集合,無需cookie時傳入null值</param>
        /// <param name="filesSaveAddress">上傳文件集合《控件名,上傳文件的保存位置(包括"文件名"."擴(kuò)展名")》,無需上傳時傳入null值</param>
        /// <returns>返回請求結(jié)果字符串,返回為null代表請求失敗</returns>
        public String setFilesToHttpWebServer(String url, Hashtable data, CookieCollection cookies, Hashtable filesSaveAddress)
        {
            //用于緩存服務(wù)器端傳輸回來的結(jié)果字符串
            string result = null;

            if (string.IsNullOrEmpty(url))
            {
                return null;//傳入?yún)?shù)異常
            }


            //用于分割信息部分的分隔符(不能與消息原文沖突)
            String boundary = "HttpWebTool" + DateTime.Now.Ticks;
            //結(jié)束分隔符數(shù)據(jù)流
            byte[] andBoundary = Encoding.UTF8.GetBytes("--" + boundary + "--");
            //新行字符串?dāng)?shù)據(jù)流
            byte[] newline = Encoding.UTF8.GetBytes("\r\n");
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                //請求方式
                req.Method = "POST";
                //聲明客戶端只接收txt類型的內(nèi)容
                req.Accept = "text/plain";
                //以消息的形式向服務(wù)器傳遞參數(shù)和數(shù)據(jù)流
                req.ContentType = "multipart/form-data; boundary=" + boundary;
                //設(shè)置cookie盒子(客戶端請求的cookie和服務(wù)器端返回的cookie就放在此盒子中)
                CookieContainer cookieContainer = new CookieContainer();
                if (sessionidCookie != null && !string.IsNullOrEmpty(sessionidCookie.Domain))
                {
                    cookieContainer.Add(sessionidCookie);
                }
                if (cookies != null)
                {
                    cookieContainer.Add(cookies);//添加調(diào)用者傳入的cookie集合
                }
                req.CookieContainer = cookieContainer;
                //用于累計數(shù)據(jù)流長度,初始化為0
                long dataCount = 0;
                byte[] parameterBytes = getParameterBytes(data, boundary);
                if (parameterBytes != null && parameterBytes.Length>0)
                {
                    //累計請求參數(shù)字符串?dāng)?shù)據(jù)流大小
                    dataCount += parameterBytes.Length;
                }
                //<控件名,上傳文件的消息頭部分字符流byte[]>
                Hashtable uploadFileDeclareBytesSet = new Hashtable();
                //如果有要上傳的文件
                if (filesSaveAddress != null && filesSaveAddress.Count > 0)
                {
                    foreach (DictionaryEntry de in filesSaveAddress)
                    {
                        //如果將要上傳的文件存在
                        if (File.Exists(de.Value.ToString()))
                        {
                            byte[] uploadFileDeclareBytes = getUploadFileDeclareBytes(de, boundary);
                            if (uploadFileDeclareBytes!=null)
                            {
                                //累計上傳文件消息頭部描述字符串?dāng)?shù)據(jù)流大小
                                dataCount += uploadFileDeclareBytes.Length;
                                //累計上傳文件正文數(shù)據(jù)流大小
                                dataCount += new FileInfo(de.Value.ToString()).Length;
                                //累計新行字符串?dāng)?shù)據(jù)流數(shù)據(jù)流大小
                                dataCount += newline.Length;
                                uploadFileDeclareBytesSet.Add(de.Key.ToString(), uploadFileDeclareBytes);
                            }
                        }
                    }
                }
                //如果有數(shù)據(jù)流
                if (dataCount>0)
                {
                    //累計結(jié)束分隔符數(shù)據(jù)流大小
                    dataCount += andBoundary.Length;
                    //請求數(shù)據(jù)流的長度
                    req.ContentLength = dataCount;

                    using (Stream requestStream = req.GetRequestStream())
                    {
                        if (parameterBytes != null && parameterBytes.Length > 0)
                        {
                            requestStream.Write(parameterBytes, 0, parameterBytes.Length);
                        }
                        if (filesSaveAddress != null && filesSaveAddress.Count > 0)
                        {
                            foreach (DictionaryEntry de in filesSaveAddress)
                            {
                                if (File.Exists(de.Value.ToString()))
                                {
                                    byte[] uploadFileDeclareBytes = (byte[])uploadFileDeclareBytesSet[de.Key.ToString()];
                                    requestStream.Write(uploadFileDeclareBytes, 0, uploadFileDeclareBytes.Length);
                                    using (FileStream fileStream = new FileStream(de.Value.ToString(), FileMode.Open, FileAccess.Read))
                                    {
                                        //建立字節(jié)組,并設(shè)置它的大小是多少字節(jié)
                                        byte[] bytes = new byte[10240];
                                        int n = -1;
                                        while ((n = fileStream.Read(bytes, 0, bytes.Length)) > 0)
                                        {
                                            requestStream.Write(bytes, 0, n); //將指定字節(jié)的流信息寫入文件流中
                                        }
                                    }
                                    requestStream.Write(newline, 0, newline.Length);
                                }
                            }
                        }

                        requestStream.Write(andBoundary, 0, andBoundary.Length);
                    }
                }

                //接收返回值
                using (HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse()) {
                    using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) {
                        result = reader.ReadToEnd().Trim();
                    }
                    if (myResponse.Cookies["SESSIONID"] != null)
                    {
                        sessionidCookie = myResponse.Cookies["SESSIONID"];
                    }
                    else
                    {
                        if (myResponse.Cookies["JSESSIONID"] != null)
                        {
                            sessionidCookie = myResponse.Cookies["JSESSIONID"];
                        }
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("請查看傳入?yún)?shù)是否正確或者服務(wù)器是否關(guān)閉");
            }


            return result;
        }
        /// <summary>
        /// 獲得參數(shù)data的消息數(shù)據(jù)流,以"\r\n"結(jié)尾
        /// </summary>
        /// <param name="data">請求參數(shù)集合,無需參數(shù)時傳入null值</param>
        /// <param name="boundary">消息分隔符</param>
        /// <returns>返回參數(shù)data的數(shù)據(jù)流,返回為空代表獲得失敗</returns>
        private byte[] getParameterBytes(Hashtable data, String boundary)
        {
            byte[] parameterBytes = null;

            //如果有請求參數(shù)
            if (data != null && data.Count > 0)
            {
                string parameterStr = "";
                foreach (DictionaryEntry de in data)
                {
                    parameterStr += "--" + boundary;
                    parameterStr += "\r\n" + "Content-Disposition: form-data;name=\"" + de.Key.ToString() + "\"";
                    parameterStr += "\r\n" + "Content-Type: text/plain; charset=UTF-8";
                    parameterStr += "\r\n\r\n" + de.Value.ToString();
                    parameterStr += "\r\n";
                }
                if (!string.IsNullOrEmpty(parameterStr))
                {
                    parameterBytes = Encoding.UTF8.GetBytes(parameterStr);//將上傳字符串?dāng)?shù)據(jù)打包成數(shù)據(jù)流
                }
            }

            return parameterBytes;
        }
        /// <summary>
        /// 獲得上傳文件的消息頭部分字符流,以"\r\n\r\n"結(jié)尾
        /// </summary>
        /// <param name="de">上傳文件《控件名,上傳文件的保存位置(包括"文件名"."擴(kuò)展名")》</param>
        /// <param name="boundary">消息分隔符</param>
        /// <returns>返回上傳文件的消息頭部分字符流,返回會為null代表獲得失敗</returns>
        private byte[] getUploadFileDeclareBytes(DictionaryEntry de, String boundary)
        {
            byte[] uploadFileDeclareBytes = null;

            //上傳文件的消息頭描述部分
            string uploadFileDeclareStr = "";
            uploadFileDeclareStr += "--" + boundary;
            uploadFileDeclareStr += "\r\n" + "Content-Disposition: form-data;name=\"" + de.Key.ToString() + "\"; filename=\"" + de.Value.ToString() + "\"";
            uploadFileDeclareStr += "\r\n" + "Content-Type: application/octet-stream";
            uploadFileDeclareStr += "\r\n\r\n";
            if (!string.IsNullOrEmpty(uploadFileDeclareStr))
            {
                uploadFileDeclareBytes = Encoding.UTF8.GetBytes(uploadFileDeclareStr);//將上傳字符串?dāng)?shù)據(jù)打包成數(shù)據(jù)流
            }


            return uploadFileDeclareBytes;
        }


    }
}
內(nèi)容所有權(quán)屬于越康體育(專業(yè)從事體質(zhì)測試儀,學(xué)生體質(zhì)測試儀的研究)

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI