.Net 上传文件IFormFile

 public async Task<ResultEntity> UploadUserAvatarAsync(IFormFile file, CancellationToken cancellationToken)
 {
     try
     {

         if (file.Equals("") || file == null || file.Length == 0)
         {
             this.ResultEntity.Result = false;
             this.ResultEntity.ErrorMessage = GetMessage("ME0024");
         }

         // 获取当前的工作路径
         var currentDirectory = Directory.GetCurrentDirectory();

         if (currentDirectory != null)
         {

             // 创建名为image的文件夹路径
             var imagePath = Path.Combine(currentDirectory, "image");

             if (!Directory.Exists(imagePath))
             {
                 Directory.CreateDirectory(imagePath);
             }

             // 拼接文件路径
             var filePath = Path.Combine(imagePath, file.FileName);

             Console.WriteLine(filePath);

             // 保存到指定的路径
             using (FileStream stream = new FileStream(filePath, FileMode.Create))
             {
                 await file.CopyToAsync(stream);
             }
             this.ResultEntity.Result = true;
             this.ResultEntity.Message = GetMessage("MI0001");

             this.ResultEntity.Data = file;
         }
         else
         {
             this.ResultEntity.Result = false;
         }

         return this.ResultEntity;
     }catch (Exception ex)
     {
         throw ex;
     }

 }

  

posted @ 2024-05-29 11:20  XiangdxDu  阅读(104)  评论(0编辑  收藏  举报