net core 100个案例

1.net core 上传文件,后台保存

 [HttpPost]
        [Route("postfile")]
        public string UploadAsync()
        {
            try
            {
                var files = HttpContext.Request.Form.Files;
                if (files.Count < 0)
                    return "失败";
                foreach (var formFile in files)
                {
                    var filePath = @"C:\1\" + formFile.FileName.Substring(formFile.FileName.LastIndexOf("\\") + 1);

                    if (formFile.Length > 0)
                    {
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            formFile.CopyToAsync(stream);
                        }
                    }
                }
                return "成功";
            }
            catch (Exception ex)
            {
                return "失败2";
            }


        }

  

2.上传文件-转为base64-保存指定目录

[HttpPost]
        [Route("postfile")]
        public string UploadAsync()
        {
            try
            {
                var files = HttpContext.Request.Form.Files;
                if (files.Count < 0)
                    return "失败";
                long fileSize = files.Sum(f => f.Length) / 1024;//由字节转为kb
                Stream fs = files[0].OpenReadStream();//将文件转为流
                string v = FileToBase64(fs);
                using (StreamWriter sw = new StreamWriter(@"G:\Users\wuxiaodong.GWMFC\Desktop\111.txt"))
                {
                    sw.WriteLine(v);
                }
                return "成功";
            }
            catch (Exception ex)
            {
                return "失败2";
            }


        }

  

你可能感兴趣的:(net core 100个案例)