.Net Core Web Api ve Angular 4 / 2 ile Dosya Yükleme

Herkese merhaba!

Angular 4 ve ASP.NET Core Web Api kullanarak geliştirdiğim uygulamamda dosya yükleme işlemi için epey bir zaman harcadım.
Belki bu yazı sayesinde size zaman tasarrufu ettirebilirim.


1. Angular 2/4 Front End Bölümü

Basitçe, bir butonla tetikleyebileceğimiz ara yüzü oluşturalım.

<input #fileInput type="file"/>
<button (click)="addFile()">Add</button>

2. Angular 2 / 4 Component Bölümü

Buradaki ViewChild alanı html sayfasındaki input'umuza bir referanstır.

@ViewChild("fileInput") fileInput;

addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
let fileToUpload = fi.files[0];
this.uploadService
.upload(fileToUpload)
.subscribe(res => {
console.log(res);
});
}
}


3. Angular 2 / 4 Dosya Yükleme Servisi

Angular4 uygulamanızda api ile iletişim kurduracağınız bir service oluşturmanız gerekiyor.


private baseUrl = 'http://localhost:11111/api/';
private _http: Http;
constructor(http: Http) {
this._http = http;
}

upload(fileToUpload: any) {
const uploadFileUrl = this.baseUrl + 'Upload'; // Upload: apideki methot adı
const formData = new FormData();
formData.append('file', fileToUpload);

return this._http.post(uploadFileUrl, formData);
}

4. .Net Core Web Api Bölümü


/// <summary>
/// Birden fazla dosya yüklenecekse ICollection<IFormFile> şeklinde parametrenizi değiştirin
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[HttpPost]
[Route("/api/upload")]
public async Task Upload(IFormFile file)
{
if (file == null)
{
throw new Exception("File is null");
}

if (file.Length == 0)
{
throw new Exception("File is empty");
}

using (Stream stream = file.OpenReadStream())
{
using (var binaryReader = new BinaryReader(stream))
{
var fileContent = binaryReader.ReadBytes((int)file.Length);
// Bu bölümde await diyerek dosya yükleme metodunuzu çağırın
}
}
}



Yorumlar

Bu blogdaki popüler yayınlar

HATA 2 || Subquery returned more than 1 value.

Kolon Adı Bilinen Tabloyu Bulmak

StyleCop || Nedir? Nasıl kurulur? StyleCop Settings?