csharp 上传文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 上传文件相关的知识,希望对你有一定的参考价值。

        /// <summary>
        /// HttpUploadFile
        /// </summary>
        /// <param name="url"></param>
        /// <param name="files"></param>
        /// <param name="data"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public string HttpUploadFile(string url, string[] files, NameValueCollection data, Encoding encoding)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endbytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            //1.HttpWebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Credentials = CredentialCache.DefaultCredentials;

            using (var stream = request.GetRequestStream())
            {
                //1.1 key/value
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                if (data != null)
                {
                    foreach (string key in data.Keys)
                    {
                        stream.Write(boundarybytes, 0, boundarybytes.Length);
                        string formitem = string.Format(formdataTemplate, key, data[key]);
                        byte[] formitembytes = encoding.GetBytes(formitem);
                        stream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }

                //1.2 file
                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                for (int i = 0; i < files.Length; i++)
                {
                    stream.Write(boundarybytes, 0, boundarybytes.Length);
                    string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
                    byte[] headerbytes = encoding.GetBytes(header);
                    stream.Write(headerbytes, 0, headerbytes.Length);
                    using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
                    {
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            stream.Write(buffer, 0, bytesRead);
                        }
                    }
                }

                //1.3 form end
                stream.Write(endbytes, 0, endbytes.Length);
            }
            //2.WebResponse
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                return stream.ReadToEnd();
            }
        }


//测试方法
        public void Test()
        {
            //生产环境还未发布,该URL还不可用。
            //var url = "http://srm.strongfood.com.cn/Views/Archived/DocumentUploadService.ashx";
            var url = "http://172.17.10.23:9999/Views/Archived/DocumentUploadService.ashx";
            var fileName1 = @"C:\Users\Public\Pictures\Sample Pictures\Koala.jpg";
            var fileName2 = @"C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg";

            //通过表单的方式传递客户端凭证,目前这两项的值是固定的
            NameValueCollection data = new NameValueCollection();
            data.Add("appid", "03BBDD81-D6CC-4364-968E-ADACC1211BAF");
            data.Add("seccode", "KTlhcGOg0xZKrYpqlhid8372BYCU5YHLR31s380OmEd9mRQDuv1vcwl75B3NaPha");
            var result = HttpUploadFile(url, new[] { fileName1, fileName2, fileName3 }, data, Encoding.UTF8);
            Console.WriteLine(result);
        }

以上是关于csharp 上传文件的主要内容,如果未能解决你的问题,请参考以下文章

csharp 上传的文件限制(IIS Express)

csharp Asynch文件上传器

csharp 上传文件和检查大小和类型

csharp C#多部分文件上传

csharp 上传文件web api 2

csharp 上传文件