控制台 访问 MVC WEB API 实现文件上传

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Collections.Specialized;
namespace UploadSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //上传方法1
            //WebClient webclient = new WebClient();
            //webclient.UploadFile("http://localhost:3890/api/UploadFile", @"E:\20120704_商场广告机.pdf");
            //上传方法2
            //Console.WriteLine(Upload_Request("http://localhost:3890/api/UploadFile", @"E:\20120704_商场广告机.pdf", ""));
            HttpPostData("http://localhost:3890/api/UploadFile", 3600, "测试.pdf", @"E:\20120704_商场广告机.pdf", null);
            //上传方法3
            //UploadViaHttpClient();
            Console.WriteLine("--------------------------------");
            Console.ReadKey(true);
        }
        private static string HttpPostData(string url, int timeOut, string fileKeyName,
                                     string filePath, NameValueCollection stringDict)
        {
            //获取文件内容
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);//
            string responseContent;
            //边界
            string boundary = DateTime.Now.Ticks.ToString("x");
            HttpWebRequest uploadRequest = (HttpWebRequest)WebRequest.Create(url);//url为上传的地址
            uploadRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            uploadRequest.Method = "POST";
            uploadRequest.Accept = "*/*";
            uploadRequest.KeepAlive = true;
            uploadRequest.Headers.Add("Accept-Language", "zh-cn");
            uploadRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            uploadRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            uploadRequest.ContentLength = fileStream.Length;
            //uploadRequest.Headers["Cookie"] = uploadRequest.CookieContainer.GetCookies();//上传文件时需要的cookies
            WebResponse reponse;
            //创建一个内存流
            Stream memStream = new MemoryStream();
            //确定上传的文件路径
            if (!String.IsNullOrEmpty(filePath))
            {
                boundary = "--" + boundary;
                //添加上传文件参数格式边界
                string paramFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}\r\n";
                NameValueCollection param = new NameValueCollection();
                param.Add("fname", Guid.NewGuid().ToString() + Path.GetExtension(filePath));
                //写上参数
                foreach (string key in param.Keys)
                {
                    string formitem = string.Format(paramFormat, key, param[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    memStream.Write(formitembytes, 0, formitembytes.Length);
                }
                //添加上传文件数据格式边界
                string dataFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
                string header = string.Format(dataFormat, "Filedata", Path.GetFileName(filePath));
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                memStream.Write(headerbytes, 0, headerbytes.Length);
                //获取文件内容
                //FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                //将文件内容写进内存流
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();
                //添加文件结束边界
                byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n\n" + boundary + "\r\nContent-Disposition: form-data; name=\"Upload\"\r\n\nSubmit Query\r\n" + boundary + "--");
                memStream.Write(boundarybytes, 0, boundarybytes.Length);
                //设置请求长度
                uploadRequest.ContentLength = memStream.Length;
                //获取请求写入流
                Stream requestStream = uploadRequest.GetRequestStream();
                //将内存流数据读取位置归零
                memStream.Position = 0;
                byte[] tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                //将内存流中的buffer写入到请求写入流
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();
            }
            //获取到上传请求的响应
            reponse = uploadRequest.GetResponse();
            using (var httpStreamReader = new StreamReader(reponse.GetResponseStream(),
                                                            Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }
            uploadRequest.Abort();
            return responseContent;
        }
        static void UploadViaHttpClient()
        {
            HttpClient client = new HttpClient();
            FileStream fileStream = null;
            try
            {
                fileStream = new FileStream("C:\\Users\\Changweihua\\Pictures\\ShinePhoto\\QQ截图20140304111438.png", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true);
                // Create a stream content for the file
                var content = new StreamContent(fileStream, 1024);
                content.Headers.ContentEncoding.Add("UTF-8");
                // Create Multipart form data content, add our submitter data and our stream content
                var formData = new MultipartFormDataContent();
                formData.Add(new StringContent("Me"), "submitter");
                //文件名不能使用中文
                formData.Add(content, "filename", @"20140304111438.png");
                // Post the MIME multipart form data upload with the file
                var address = new Uri(new Uri("http://localhost:3890"), "/api/UploadFile");
                try
                {
                    var response = client.PostAsync(address, formData).Result;
                    var result = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                fileStream.Dispose();
            }
        }
    }
}


知识共享许可协议
《控制台 访问 MVC WEB API 实现文件上传》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

0 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     176.19ms