• 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("
    --" + boundary + "
    ");
    
                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}"
    
    {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}"
    Content-Type: {1}
    
    ";
                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("
    --" + boundary + "--
    ");
                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("
    --" + boundary + "
    ");
    
                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}"
    
    {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}"
    Content-Type: {1}
    
    ";
                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("
    --" + boundary + "--
    ");
                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
  • 相关阅读:
    STL map
    HDU1372 Knight Moves BFS
    HDU1072 Nightmare BFS
    discuz论坛发帖添加字段
    gridview自定义button事件 ,无法触发 onrowcommand
    discuz 怎么开启评分!!!
    discuz学习网站收集
    discuz扩展工具集合
    童话世界整理“说说”
    asp.net中Literal与label的区别
  • 原文地址:https://www.cnblogs.com/zengtianli/p/15529596.html
Copyright © 2020-2023  润新知