C# webapi 文件流 stream 两种上传方式《第一部分 文件流》

  • Post author:
  • Post category:其他


博客仅用于记录工作学习中遇到的坑,欢迎交流!

1.文件流

1.1 客户端

从上传组件中获取InputStream,转换为byte[],组装对象上传

  try{    byte[] buffer = new byte[filedata.InputStream.Length];
                filedata.InputStream.Read(buffer, 0, buffer.Length);
                var requstData = new
                {
                    file = buffer,
                    path = resultPath,
                    fileName = filename
                };
                var result = UrlRequestHelper.HttpPostRequst(ConfigurationManager.AppSettings["FileUploadPath"], JsonConvert.SerializeObject(requstData), "");
            }

httppost重写

 /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="postData"></param>        
        /// <returns></returns>
        public static string HttpPostRequst(string url, string postData, string ActionUrl)
        {
            byte[] bs = Encoding.UTF8.GetBytes(postData);

            HttpWebRequest result = (HttpWebRequest)WebRequest.Create(url + ActionUrl);
            result.ContentType = "application/json";
            result.ContentLength = bs.Length;
            result.Method = "POST";

            using (Stream reqStream = result.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }
            using (WebResponse wr = result.GetResponse())
            {
                string reader = new StreamReader(wr.GetResponseStream(),
                    Encoding.UTF8).ReadToEnd();
                return reader;
            }
        }

设置webconfig的maxRequestLength

  <!--maxRequestLength就是文件的最大字符数,最大值不能超过2个G左右,executionTimeout是超时时间-->
    <httpRuntime targetFramework="4.5" maxRequestLength="1073741824" executionTimeout="3600" requestValidationMode="2.0" />
  

1.2 webapi

配置接收最大值

  <security>
      <!--配置允许接收最大G -->
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2000000000" />
      </requestFiltering>
    </security>

由[FromBody] object bit 接收,DeserializeObject转对象

  [HttpPost]
        public string FileUp([FromBody] object bit)

        {

            lock (_lock)
            {
                string jsonstr = JsonConvert.SerializeObject(bit);
                Data res = JsonConvert.DeserializeObject<Data>(jsonstr);

                return SaveFile(res.file, res.path, res.fileName);
            }
        }

重点:byte[] 转stream  ,写入文件;

   private string SaveFile(byte[] file, string path, string fileName)
        {
            try
            {
                var serverPath = configPath;   //存储路径
                CreatePath(serverPath + @path);
                var filename = fileName;
                var filePath = string.Format(@"{0}\{1}", serverPath + @path, filename);     //保存完整路径
                var fullpath = filePath;     //流写入路径
               
                //创建文件  

                using (var ms = new MemoryStream())
                {
                    MemoryStream m = new MemoryStream(file);
                    string files = string.Format(@"{0}", fullpath);
                    FileStream fs = new FileStream(files, FileMode.OpenOrCreate);
                    m.WriteTo(fs);
                    m.Close();
                    fs.Close();
                    m = null;
                    fs = null;
                    return fullpath;
                }
            }
            catch (Exception ex)
            {
                throw ex;

            }
        }

遇到的坑:文件夹权限问题(如果没遇到可以不用)

 /// <summary>
        /// 创建文件路径
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        private void CreatePath(string filepath)
        {
            if (!Directory.Exists(filepath))
            {
                var securityRules = new DirectorySecurity();
                securityRules.AddAccessRule(new FileSystemAccessRule(System.Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow));
                securityRules.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
                securityRules.AddAccessRule(new FileSystemAccessRule("NETWORK SERVICE", FileSystemRights.FullControl, AccessControlType.Allow));
                Directory.CreateDirectory(filepath, securityRules);
            }
        }

学习笔记!



版权声明:本文为qq_22098679原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。