编程语言
首页 > 编程语言> > C# 上传文件

C# 上传文件

作者:互联网

#region 文件上传
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filePath"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static HttpWebResponse CreatePostUploadFileResponse(string url, string filePath, IDictionary<string, string> parameters = null, int timeout = 30000, Encoding requestEncoding = null)
        {
            if (requestEncoding == null)
            {
                requestEncoding = System.Text.Encoding.UTF8;
            }
            var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            httpWebRequest.Method = "POST";
            httpWebRequest.Accept = "*/*";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Timeout = timeout;
            httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;

            HttpWebResponse reponse;
            var stream = httpWebRequest.GetRequestStream();

            var formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            //添加其他参数
            if (!(parameters == null || parameters.Count == 0))
            {
                foreach (string key in parameters.Keys)
                {
                    string formitem = string.Format(formdataTemplate, key, parameters[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    stream.Write(formitembytes, 0, formitembytes.Length);
                }
            }
            stream.Write(boundarybytes, 0, boundarybytes.Length);
            var fileName = Path.GetFileName(filePath);
            var extension = Path.GetExtension(fileName);
            var headerTemplate = "Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";
            string header = string.Format(headerTemplate, fileName, GetContentType(extension));
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            stream.Write(headerbytes, 0, headerbytes.Length);

            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                stream.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(trailer, 0, trailer.Length);
            stream.Close();


            //成功回傳結果
            reponse = httpWebRequest.GetResponse() as HttpWebResponse;
            return reponse;
        }







        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filePath"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static HttpWebResponse CreatePostUploadFileResponse(string url, string fileName, MemoryStream fileStream, IDictionary<string, string> parameters = null, int timeout = 30000, Encoding requestEncoding = null)
        {
            if (requestEncoding == null)
            {
                requestEncoding = System.Text.Encoding.UTF8;
            }
            var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            httpWebRequest.Method = "POST";
            httpWebRequest.Accept = "*/*";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Timeout = timeout;
            httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;

            HttpWebResponse reponse;
            var stream = httpWebRequest.GetRequestStream();

            var formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            //添加其他参数
            if (!(parameters == null || parameters.Count == 0))
            {
                foreach (string key in parameters.Keys)
                {
                    string formitem = string.Format(formdataTemplate, key, parameters[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    stream.Write(formitembytes, 0, formitembytes.Length);
                }
            }
            stream.Write(boundarybytes, 0, boundarybytes.Length);
            var extension = Path.GetExtension(fileName);
            var headerTemplate = "Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";
            string header = string.Format(headerTemplate, fileName, GetContentType(extension));
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            stream.Write(headerbytes, 0, headerbytes.Length);

            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                stream.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(trailer, 0, trailer.Length);
            stream.Close();


            //成功回傳結果
            reponse = httpWebRequest.GetResponse() as HttpWebResponse;
            return reponse;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileExtension"></param>
        /// <returns></returns>
        public static string GetContentType(string fileExtension)
        {
            var mimeTypes = new Dictionary<String, String>
            {
                {".bmp", "image/bmp"},
                {".gif", "image/gif"},
                {".jpeg", "image/jpeg"},
                {".jpg", "image/jpeg"},
                {".png", "image/png"},
                {".tif", "image/tiff"},
                {".tiff", "image/tiff"},
                {".doc", "application/msword"},
                {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
                {".pdf", "application/pdf"},
                {".ppt", "application/vnd.ms-powerpoint"},
                {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
                {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
                {".xls", "application/vnd.ms-excel"},
                {".csv", "text/csv"},
                {".xml", "text/xml"},
                {".txt", "text/plain"},
                {".zip", "application/zip"},
                {".ogg", "application/ogg"},
                {".mp3", "audio/mpeg"},
                {".wma", "audio/x-ms-wma"},
                {".wav", "audio/x-wav"},
                {".wmv", "audio/x-ms-wmv"},
                {".swf", "application/x-shockwave-flash"},
                {".avi", "video/avi"},
                {".mp4", "video/mp4"},
                {".mpeg", "video/mpeg"},
                {".mpg", "video/mpeg"},
                {".qt", "video/quicktime"}
            };

            // if the file type is not recognized, return "application/octet-stream" so the browser will simply download it
            return mimeTypes.ContainsKey(fileExtension) ? mimeTypes[fileExtension] : "application/octet-stream";
        }


        #endregion
View Code

 

标签:文件,string,stream,Encoding,C#,System,httpWebRequest,var,上传
来源: https://www.cnblogs.com/zengtianli/p/15529596.html