1. 程式人生 > >C# webapi 檔案流 stream 兩種上傳方式《第一部分 檔案流》

C# webapi 檔案流 stream 兩種上傳方式《第一部分 檔案流》

 部落格僅用於記錄工作學習中遇到的坑,歡迎交流!

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);
            }
        }

學習筆記!