title: Trying to/How To post an Image file from Angular front end to .NET CORE Backend API --
body: <p>I want to know what is the best way to do this.</p>
  
  <p>From my Angular 8 app, I am selecting an img file and would like to send this image file to a .NET Core API backend. The backend service should save this img in
  the database.</p>
  
  <p>html for my image selector -</p>
  
  <pre><code>&lt;div class="image-picker" (click)="fileInput.click()"&gt;
    &lt;mat-icon [class.small]="imageUrl"&gt;file_upload&lt;/mat-icon&gt;
    &lt;canvas width="500" height="380" #canvas hidden="true"&gt;&lt;/canvas&gt;
    &lt;input #fileInput type="file" hidden="true" (change)="imageDataChanged($event)"&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>respective .ts code -</p>
  
  <pre><code>imageDataChanged($event) {
      var file = $event.target.files[0];
  
  
      console.log(file);
  
      var reader = new FileReader();
  
      // get data from file input and emit as dataUrl
      reader.addEventListener("load", () =&gt; {
        var ctx = this.canvas.nativeElement.getContext('2d');
        this.imageUrl = reader.result;
        this.imagePicked.emit(this.imageUrl);
      }, false);
  
      if (file) {
        reader.readAsDataURL(file);
      }
    }
  </code></pre>
  
  <p>So I get in my console, details related to the file I selected. Like name, size, date, datemodified ..... Upon clicking a submit button I'd like to post this file to the backend API. My question is - in what format and how. base64 image? What's the code for that. How would I do that. Like I said, my backend is in .NET Core.</p>
  
  <p>Here's the code I attempted -</p>
  
  <pre><code>[HttpPost]
          [Route("CaptureSaveImg")]
          public IActionResult CaptureSaveImg(HttpContext context)
          {
              string imageName = null;
              var httpRequest = context.Request;
  
              var postedFile = httpRequest.Form.Files["Image"];
  
              try
              {
                  if(postedFile!=null)
                  {
                      var fileName = postedFile.FileName;
  
                      var myUniqueFileName = Convert.ToString(Guid.NewGuid());
  
                      var fileExtension = Path.GetExtension(fileName);
  
                      var newFileName = string.Concat(myUniqueFileName, fileExtension);
  
                      var filepath = Path.Combine(_environment.WebRootPath, "CameraPics") + $@"\{newFileName}";
  
                      if (!string.IsNullOrEmpty(filepath))
                      {
                          // Storing Image in Folder  
                          StoreInFolder(postedFile, filepath);
                      }
  
                      var imageBytes = System.IO.File.ReadAllBytes(filepath);
                      if (imageBytes != null)
                      {
                          StoreInDatabase(imageBytes);
                      }
  
                      return Json(new { Success = true, Message = "Image Saved." });
                  }
                  else
                  {
                      return Json(new { Success = false, Message = "An error occurred while saving the image." });
                  }
              }
              catch(Exception exp)
              {
                  return Json(new { Success =false, Message="An unexpected error occurred!"});
              }
          }
  
  
  private void StoreInDatabase(byte[] imageBytes)
          {
              try
              {
                  if (imageBytes != null)
                  {
                      string base64String = Convert.ToBase64String(imageBytes, 0, imageBytes.Length);
                      string imageUrl = string.Concat("data:image/jpg;base64,", base64String);
                      ImageStore imageStore = new ImageStore()
                      {
                          CreateDate = DateTime.Now,
                          ImageBase64String = imageUrl,
                          ImageId = 0
                      };
                      _context.ImageStores.Add(imageStore);
                      _context.SaveChanges();
                  }
              }
              catch (Exception exp)
              {
                  throw exp.InnerException;
              }
          }
  
          private void StoreInFolder(IFormFile file, string fileName)
          {
              try
              {
                  using (FileStream fs = System.IO.File.Create(fileName))
                  {
                      file.CopyTo(fs);
                      fs.Flush();
                  }
              }
              catch (Exception exp)
              {
                  throw exp.InnerException;
              }
  
          }
  </code></pre>
  
  <p>html for button click -</p>
  
  <pre><code>&lt;button class="btn btn-primary btn-lg btn-block" type="button" (click)="OnSubmit(Image)" &gt;UPLOAD&lt;/button&gt;
  </code></pre>
  
  <p>.ts for button click -</p>
  
  <pre><code>OnSubmit(file: File)
    {
      this.userRestService.uploadImage(this.fileToUpload)
        .subscribe((data: any) =&gt; {
          console.log('Done successfully! '+data.Message);
          this.imageUrl = null;
        });
    }
  </code></pre>
  
  <p>In the use-rest service -</p>
  
  <pre><code>fileToUpload: File = null;  
  
  uploadImage(file: File) {
      var reqHeader = new HttpHeaders({ 'No-Auth': 'True' });
  
      const formData: FormData = new FormData();
      formData.append('Image', file, file.name);
  
      return this.http.post(this.baseUrl +'CaptureSaveImg', formData, { headers: reqHeader });
    }
  </code></pre>
  
  <p>I want to first save it in a local folder path and then from there, read the file and save in DB. I do9 understand that when I am trying to post it as
  fileToUpload, it is sending null probably.</p>
  
  <p>Problem I am facing - what do I post/send from the front end to the API. How. Can you show me some code that would achive this. Can you give me a step by step guide to achieve this.</p>
  
  <p>Feel free to ask for more details on what I attempted, to gain better insight.
  Thanks</p>
  
  <p>UPDATE:</p>
  
  <p>I forgot to mention earlier that my image picker component is basically a separate angular component that I am using as  in my main page. So the imageDataChanged($event) code is also in that component. Let me post.</p>
  
  <pre><code>&lt;input #fileInput type="file" hidden="true" (change)="imageDataChanged($event)"&gt;
  </code></pre>
  
  <p>The .ts code -</p>
  
  <pre><code>imageDataChanged($event) {
      var file = $event.target.files[0];
      this.ds.selectedFile = file;
  
      if (file.length===0) {
        return;
      }
  
      var reader = new FileReader();
  
      // get data from file input and emit as dataUrl
      reader.addEventListener("load", () =&gt; {
        var ctx = this.canvas.nativeElement.getContext('2d');
        this.imageUrl = reader.result;
        this.imagePicked.emit(this.imageUrl);
      }, false);
  
      if (file) {
        reader.readAsDataURL(file);
      }
  
      const formData = new FormData();
  
      formData.append(file.name, file);
  
      this.ds.formDataPost = formData;
  
    }
  </code></pre>
  
  <p>Here ds is nothing but an intermediate data sharing injectable class.</p>
  
  <pre><code>@Injectable()
  export class DataSharingService {
  
    public selectedFile: any;
  
    public formDataPost: any;
  
  }
  </code></pre>
  
  <p>Now, my OnSubmit code -</p>
  
  <pre><code>OnSubmit()
    {
      console.log(this.ds.formDataPost);
  
      const uplRequest = new HttpRequest('POST', this.baseUrl + '/CaptureSaveImg', this.ds.formDataPost, { reportProgress: true });
  
      this.http.request(uplRequest)
        .subscribe((data: any) =&gt;
        {
          if (data.Success == "true")
          {
            console.log("Upload successful.");
          }
          else
          {
            console.log("Problem while uploading file.");
          }
        })
    }
  </code></pre>
  
  <p>I'm just getting error - <strong><em>core.js:6014 ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.</em></strong></p>
  
  <p>I think I am close. Any conversion needed? Or format of data? </p>