Angular 4 – Upload file

Hướng dẫn Upload file trong Angular4

Backend:

Link demo: http://angular.tuanitpro.com/#/uploader

  • Username: tuanitpro
  • Password: 123456

uploader.component.css

input[type='file']{
    display: none;
}
#uploader{
    width:100%; color:#fff; 
    font-family:Verdana, Geneva, Tahoma, sans-serif; 
     background:#0094ff;
      text-align:center;
       padding:50px;
        cursor:pointer;
}

uploader.component.html

<div class="container body">
  <div class="main_container">

    <div class="right_col" role="main">


      <div class="">
        <div class="clearfix"></div>
        <div class="row">
          <div class="col-md-12">
            <h2>Angular 4 - Upload file</h2>
          </div>

          <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel" style="height: auto;">

              <div class="x_content">

                <input type="file" id="fileUploadInput" accept="images/*" (change)="fileChange($event)" />
                <div id="uploader"                    (click)="doUploadFile()">
                 <i class="fa fa-picture-o"></i> {{uploadResult.uploadingText}}
                </div>
                <div class="progress progress-striped" *ngIf="uploadResult.progress > 0">
                  <div class="progress-bar progress-bar-success"  [ngStyle]="{'width':  uploadResult.progress+'%'}">{{uploadResult.progress}}%</div>
                </div>
                <img  *ngIf="uploadResult.fileUrl" src="{{uploadResult.fileUrl}}" style="width:100%;" class="img-response">
              </div>
            </div>
          </div>
        </div>
      </div>





    </div>

  </div>
</div>

uploader.component.ts

import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Http } from '@angular/http';

import $ from 'jquery/dist/jquery.min';

@Component({
  selector: 'app-uploader',
  templateUrl: './uploader.component.html',
  styleUrls: ['./uploader.component.css']
})
export class UploaderComponent implements OnInit {
  uploadingText = 'Chọn file (chỉ chấp nhận file ảnh)';
  uploadResult: any = {
    progress: 0,
    uploadingText: this.uploadingText,
    fileUrl: null
  }
  constructor(private title: Title) { }
  ngOnInit() {
    this.title.setTitle("Angular 4 - Upload file"); 
  }
  doUploadFile() {
    this.uploadResult.progress = 0;
    this.uploadResult.fileUrl = null;
    this.uploadResult.uploadingText = this.uploadingText;
    $("#fileUploadInput").trigger("click");
  }
  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      let file: File = fileList[0];
      let formData: FormData = new FormData();
      formData.append('uploadFile', file);
      let xhr: XMLHttpRequest = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let json = JSON.parse(xhr.response);
            let fileUrl = 'http://minhquandalat.com/uploads/' + json.Name;
            this.uploadResult.progress = 100;
            this.uploadResult.fileUrl = fileUrl;
            this.uploadResult.uploadingText = "Hoàn thành";

          } else {
            console.log(xhr.response);
          }
        }
      };
      xhr.upload.onprogress = (event) => {
        this.uploadResult.uploadingText = "Đang tải ảnh lên...";
        let percentVal = Math.round(event.loaded / event.total * 100);
        this.uploadResult.progress = percentVal;
      };
      xhr.open('POST', "http://minhquandalat.com/api/FileUpload", true);
      xhr.send(formData);
    }
  }
}

Happy coding !

Published by

tuanitpro

Tôi là Lê Thanh Tuấn, và tôi chia sẻ những điều mình cho rằng nó là thú vị, hay giúp ích cho bạn!

Leave a Reply