.NET 文件上传和文件接收

有时候,我们需要在后台端发起向指定的“文件接收接口”的文件传输请求,可以采用HttpWebRequest方式实现文件传输请求。

1、HttpWebRequest文件传输请求的代码如下:

其中,url为外部的文件接收接口,url中可以跟多个参数,如: http:project/Weixin/SaveUploadFile?path={0}

filePath为待上传文件的物理路径

         /// <summary>
        /// 传输文件到指定接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filePath">文件物理路径</param>
        /// <returns></returns>
        public static string PostFile(string url, string filePath)
        {
            // 初始化HttpWebRequest
            HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            // 封装Cookie
            Uri uri = new Uri(url);
            Cookie cookie = new Cookie("Name", DateTime.Now.Ticks.ToString());
            CookieContainer cookies = new CookieContainer();
            cookies.Add(uri, cookie);
            httpRequest.CookieContainer = cookies;

            if (!File.Exists(filePath))
            {
                return "文件不存在";
            }
            FileInfo file = new FileInfo(filePath);

            // 生成时间戳
            string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}--\r\n", strBoundary));

            // 填报文类型
            httpRequest.Method = "Post";
            httpRequest.Timeout = 1000 * 120;
            httpRequest.ContentType = "multipart/form-data; boundary=" + strBoundary;

            // 封装HTTP报文头的流
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append(Environment.NewLine);
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append("file");
            sb.Append("\"; filename=\"");
            sb.Append(file.Name);
            sb.Append("\"");
            sb.Append(Environment.NewLine);
            sb.Append("Content-Type: ");
            sb.Append("multipart/form-data;");
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString());

            // 计算报文长度
            long length = postHeaderBytes.Length + file.Length + boundaryBytes.Length;
            httpRequest.ContentLength = length;

            // 将报文头写入流
            Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            
//文件流循环写入
byte[] buffer = new byte[4096]; int bytesRead = 0; using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } } // 将报文尾部写入流 requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); // 关闭流 requestStream.Close(); using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse()) { StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); var rs = sr.ReadToEnd(); return rs; //Console.WriteLine("反馈结果" + responseString); } }

2、文件接收端:url接口代码如下

其中,JsonResultData类为自身项目中的一个传输类;

Base.Config.BConfig.GetConfigToString(path) 为自身项目中在配置文件中根据键获得值的方法。

        /// <summary>
        /// 保存平台端传来的文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public ActionResult SaveUploadFile(string path, HttpPostedFileBase file)
        {
            JsonResultData result = new JsonResultData();

            try
            {
                string myPath = Base.Config.BConfig.GetConfigToString(path);//配置文件中读取路径

                if (string.IsNullOrWhiteSpace(myPath))
                {
                    throw new Exception("未配置附件存放路径,请联系管理员配置"+path);
                }
                if (Directory.Exists(myPath) == false)
                {
                    Directory.CreateDirectory(myPath);
                }

                file.SaveAs(myPath + "\\" + file.FileName);
                result.IsSuccess = true;
                result.Message = "文件保存成功!"+path;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
                BLog.Write(BLog.LogLevel.WARN, "上传附件出错:" + ex.ToString());
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

 

posted on 2019-07-03 11:57  儿时精神  阅读(2081)  评论(0编辑  收藏  举报

导航