Wednesday, June 21, 2017

Upload something from Angular 2 with the both the file input type HTML control and Observable.

If this is at your component's template...

<input type="file" (change)="uploadFile($event)">

 
 

...you may kick off this in the component itself:

uploadFile(event:any):void{
   let filePath = event.target.value;
   if (filePath){
      this.myService.uploadFile(event.target.files[0]);
   }
}

 
 

That in turn may reach into your service for this method. Note that Headers and RequestOptions must be imported from '@angular/http' while FormData just seems to magically work.

public uploadFile(file: any): void {
   var url = "http://www.example.com/api/whatever/";
   let formData:FormData = new FormData();
   formData.append('uploadFile', file, file.name);
   let headers = new Headers();
   headers.append('Content-Type', 'multipart/form-data');
   headers.append('Accept', 'application/json');
   let options = new RequestOptions({ headers: headers });
   this.http.post(url, formData, options)
      .catch(error => Observable.throw(error))
      .subscribe(
         data => console.log('success'),
         error => console.log(error)
   )
}

 
 

At the ASP.NET Web API side of things you could have an endpoint like so in a .NET Core Microsoft.AspNetCore.Mvc.Controller:

[HttpPost]
[Route("api/whatever")]
public void SaveStuff()
{
   HttpRequest request = this.Request;
   IFormFile file = request.Form.Files[0];
   using (var reader = new StreamReader(file.OpenReadStream()))
   {
      var fileContent = default(byte[]);
      using (var memoryStream = new MemoryStream())
      {
         var buffer = new byte[file.Length];
         var bytesRead = default(int);
         while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
         {
            memoryStream.Write(buffer, 0, bytesRead);
         }
         fileContent = memoryStream.ToArray();
      }
      using (var writer = new BinaryWriter(System.IO.File.Open("C:\\x.jpg",
            FileMode.OpenOrCreate)))
      {
         writer.Write(fileContent);
      }
   }
}

 
 

Clearly the BinaryWriter stuff above is silly. It's just there to show off that the code above works. If you want the file name for the file, you could have gotten above with:

string fileName = file.FileName;

 
 

Addendum 6/26/2017: This is also legit, giving something like: image/jpeg

string contentType = file.ContentType;

No comments:

Post a Comment