Wince 6.0适用 .NET 使用HttpRequest的Post上传文件,服务端的Web API接收Post上传上来的文件 代码


         //调用的示例
         private string fileName = "InStorageData.csv";
         string filePath = parentPath + CommonHelper.UPLOAD + "\\" + fileName;//文件的全路径含文件名称及扩展名
         string strResult = CommonHelper.SendFile(filePath, new Uri(CommonHelper.strURL + "PostFormData/" + fileName));

        /// 
        /// 上传文件至服务器
        /// 
        /// 
        /// 
        public static string SendFile(string fileName, Uri uri)
        {
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uri);
            httpReq.Credentials = CredentialCache.DefaultCredentials;
            httpReq.Timeout = 60000;
            httpReq.Headers.Add("cookie", string.Format("user=rainier-soft.com;fileName={0};warehouseId={1}", Path.GetFileName(fileName), CommonHelper.WarehouseId));
            string strHtml=string.Empty;
            //httpReq.MaximumAutomaticRedirections = 4;
            //httpReq.MaximumResponseHeadersLength = 4;
            
            //时间戳

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            httpReq.ContentType = "multipart/form-data; boundary=" + boundary;
            httpReq.Method = "POST";
            
            //设置对发送的数据不使用缓存

            httpReq.AllowWriteStreamBuffering = false;

            // Build up the post message header
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"file\"; fileName=\"");
            sb.Append(Path.GetFileName(fileName));
            sb.Append("\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: application/octet-stream;charset=gb2312");
            sb.Append("\r\n");
            sb.Append("\r\n");

            string postHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

            // Build the trailing boundary string as a byte array
            // ensuring the boundary appears on a line by itself
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            FileStream fileStream=null;
            if (File.Exists(fileName))
                fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            else
                return "NOT";
            
            httpReq.ContentLength = fileStream.Length + (long)postHeaderBytes.Length + (long)boundaryBytes.Length;//Important
            // Write out the trailing boundary

            try
            {
                Stream requestStream = httpReq.GetRequestStream();

                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    requestStream.Write(buffer, 0, bytesRead);
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                requestStream.Flush();//Important
                requestStream.Close();
                requestStream.Dispose();
                fileStream.Flush();
                fileStream.Close();
                fileStream.Dispose();

                

                HttpWebResponse httpWebResponse = (HttpWebResponse)httpReq.GetResponse();
                string cookie = httpWebResponse.Headers.Get("Set-Cookie");
                string contentType = httpWebResponse.ContentType;
                Stream dataStream = httpWebResponse.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
                strHtml = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
                dataStream.Close();
                dataStream.Dispose();
                httpWebResponse.Close();
                httpWebResponse.Close();
                System.GC.Collect();
            }
            catch (Exception ex)
            {
                strHtml = "NO";
            }

            return strHtml;
        }




        /// 
        /// Post上传文件
        /// 
        /// 
        [HttpPost]
        public string PostFormData()
        {
            string postJson;
            string filesName = string.Empty;
            string pathFile;
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                return new HttpResponseException(HttpStatusCode.UnsupportedMediaType).Message;
            }

            /*****获取POST上来的文件流****/
            Stream streams = HttpContext.Current.Request.InputStream; //获取全部
            HttpPostedFile file = HttpContext.Current.Request.Files[0];
            Stream stream = file.InputStream;
            var buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            stream.Close();
            stream.Dispose();
            /*****获取POST上来的文件流****/

            try
            {
                /********从Cookies中获取文件名称******/
                int loop1;
                HttpCookieCollection myCookieCollection = HttpContext.Current.Request.Cookies;
                for (loop1 = 0; loop1 < myCookieCollection.Count; loop1++)
                {
                    if (myCookieCollection.GetKey(loop1) == "fileName")
                    {
                        filesName = myCookieCollection[loop1].Value;
                        myCookieCollection.Set(myCookieCollection[loop1]);
                        break;
                    }
                }
                /*******从Cookies中获取文件名称*******/

                /********把POST上传的文件保存到服务端的文件夹下********/
                string fileDire = HttpContext.Current.Server.MapPath("~/UpLoad/");
                //如果不存在就创建文件夹

                if (Directory.Exists(fileDire) == false)
                {
                    Directory.CreateDirectory(fileDire);
                }
                //打开文件
                pathFile = fileDire + filesName;
                if (File.Exists(pathFile))
                {
                    File.Delete(pathFile);
                    GC.Collect();
                }
                var fstream = new FileStream(pathFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                fstream.Write(buffer, 0, buffer.Length); //写二进制数组到文件

                fstream.Close(); //关闭文件
                fstream.Dispose(); //释放资源
                GC.Collect();
                postJson = Request.CreateResponse(HttpStatusCode.OK).ToString();
                postJson = HttpStatusCode.OK.ToString();
                /********把POST上传的文件保存到服务端的文件夹下********/
                //Todo: 更新上传的文件到服务端

            }
            catch (Exception ex)
            {
                return new HttpResponseException(HttpStatusCode.HttpVersionNotSupported).Message;
            }
            return postJson;
        }