博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Wince 6.0适用 .NET 使用HttpRequest的Post上传文件,服务端的Web API接收Post上传上来的文件 代码...
阅读量:5249 次
发布时间:2019-06-14

本文共 6839 字,大约阅读时间需要 22 分钟。

//调用的示例         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; }

  

转载于:https://www.cnblogs.com/wuhuisheng/p/4579952.html

你可能感兴趣的文章
C# 强制关闭当前程序进程(完全Kill掉不留痕迹)
查看>>
ssm框架之将数据库的数据导入导出为excel文件
查看>>
hdu 4284 Travel(压缩DP,4级)
查看>>
easy_install
查看>>
hdu 1423 Greatest Common Increasing Subsequence(DP 最长公共上升子序列)
查看>>
【Log4j】分包,分等级记录日志信息
查看>>
语音识别中的MFCC的提取原理和MATLAB实现
查看>>
初识Treap
查看>>
20190317 A
查看>>
poj 1564 Sum It Up
查看>>
解读ASP.NET 5 & MVC6系列
查看>>
数据库创建表空间,用户、密码,授权
查看>>
CSS实现水平垂直居中的1010种方式
查看>>
MYSQL查询增加自增长序号
查看>>
第50节:Java的当中的泛型
查看>>
PHP全栈学习笔记10
查看>>
bzoj 2302: [HAOI2011]Problem c
查看>>
bzoj 3991: [SDOI2015]寻宝游戏
查看>>
Linux学习-1进程
查看>>
理解Javascript的闭包
查看>>