{"id":746,"date":"2020-12-26T13:38:00","date_gmt":"2020-12-26T12:38:00","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=746"},"modified":"2020-12-26T15:13:35","modified_gmt":"2020-12-26T14:13:35","slug":"angular-11-image-upload-with-preview","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2020\/12\/26\/angular-11-image-upload-with-preview\/","title":{"rendered":"Angular 11 Image Upload With Preview"},"content":{"rendered":"\n<p>In this tutorial, we will learn how to upload image with preview in angular 11 app.<\/p>\n\n\n\n<p>As well as, this tutorial will guide us step by step on how to upload image in angular 11. And also use reactive form with formGroup to upload image with preview.<\/p>\n\n\n\n<h4><span class=\"has-inline-color has-vivid-cyan-blue-color\">Image Upload with Preview in Angular 11 Reactive Form<\/span><\/h4>\n\n\n\n<h4>Step 1 \u2013 Create New Angular App<\/h4>\n\n\n\n<p>First of all, open your terminal and execute the following command on it to install angular app:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ng new my-new-app<\/code><\/pre>\n\n\n\n<h4>Step 2 \u2013 Import Module<\/h4>\n\n\n\n<p>Then, Open app.module.ts file and import HttpClientModule, FormsModule and ReactiveFormsModule to app.module.ts file like following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { BrowserModule } from '@angular\/platform-browser';\nimport { NgModule } from '@angular\/core';\nimport { HttpClientModule } from '@angular\/common\/http';\nimport { FormsModule, ReactiveFormsModule } from '@angular\/forms';\n    \nimport { AppComponent } from '.\/app.component';\n    \n@NgModule({\n  declarations: &#91;\n    AppComponent\n  ],\n  imports: &#91;\n    BrowserModule,\n    HttpClientModule,\n    FormsModule,\n    ReactiveFormsModule\n  ],\n  providers: &#91;],\n  bootstrap: &#91;AppComponent]\n})\nexport class AppModule { }<\/code><\/pre>\n\n\n\n<h4>Step 3 \u2013 Add Code on View File<\/h4>\n\n\n\n<p>In this step, create simple reactive form with input file element and image tag. So, visit src\/app\/app.component.html and update the following code into it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;h1>Angular 11 Image Upload with Preview&lt;\/h1>\n    \n&lt;form &#91;formGroup]=\"myForm\" (ngSubmit)=\"submit()\">\n      \n    &lt;div class=\"form-group\">\n        &lt;label for=\"name\">Name&lt;\/label>\n        &lt;input\n            formControlName=\"name\"\n            id=\"name\"\n            type=\"text\"\n            class=\"form-control\">\n        &lt;div *ngIf=\"f.name.touched &amp;amp;&amp;amp; f.name.invalid\" class=\"alert alert-danger\">\n            &lt;div *ngIf=\"f.name.errors.required\">Name is required.&lt;\/div>\n            &lt;div *ngIf=\"f.name.errors.minlength\">Name should be 3 character.&lt;\/div>\n        &lt;\/div>\n    &lt;\/div>\n     \n    &lt;div class=\"form-group\">\n        &lt;label for=\"file\">File&lt;\/label>\n        &lt;input\n            formControlName=\"file\"\n            id=\"file\"\n            type=\"file\"\n            class=\"form-control\"\n            (change)=\"onFileChange($event)\">\n        &lt;div *ngIf=\"f.file.touched &amp;amp;&amp;amp; f.file.invalid\" class=\"alert alert-danger\">\n            &lt;div *ngIf=\"f.file.errors.required\">File is required.&lt;\/div>\n        &lt;\/div>\n    &lt;\/div>\n     \n    &lt;img &#91;src]=\"imageSrc\" *ngIf=\"imageSrc\" style=\"height: 300px; width:500px\">\n         \n    &lt;button class=\"btn btn-primary\" type=\"submit\">Submit&lt;\/button>\n&lt;\/form><\/code><\/pre>\n\n\n\n<h4>Step 4 \u2013 Use Component ts File<\/h4>\n\n\n\n<p>In this step, open the file<strong>  app.component.ts<\/strong>. Then add the following code. We import  formGroup and formControl element on component.ts file:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { Component } from '@angular\/core';\nimport { HttpClient } from '@angular\/common\/http';\nimport { FormGroup, FormControl, Validators} from '@angular\/forms';\n     \n@Component({\n  selector: 'app-root',\n  templateUrl: '.\/app.component.html',\n  styleUrls: &#91;'.\/app.component.css']\n})\nexport class AppComponent {\n   imageSrc: string;\n   myForm = new FormGroup({\n    name: new FormControl('', &#91;Validators.required, Validators.minLength(3)]),\n    file: new FormControl('', &#91;Validators.required]),\n    fileSource: new FormControl('', &#91;Validators.required])\n  });\n   \n  constructor(private http: HttpClient) { }\n     \n  get f(){\n    return this.myForm.controls;\n  }\n    \n  onFileChange(event) {\n    const reader = new FileReader();\n     \n    if(event.target.files &amp;amp;&amp;amp; event.target.files.length) {\n      const &#91;file] = event.target.files;\n      reader.readAsDataURL(file);\n     \n      reader.onload = () => {\n    \n        this.imageSrc = reader.result as string;\n      \n        this.myForm.patchValue({\n          fileSource: reader.result\n        });\n    \n      };\n    \n    }\n  }\n    \n  submit(){\n    console.log(this.myForm.value);\n    this.http.post('http:\/\/localhost:8001\/upload.php', this.myForm.value)\n      .subscribe(res => {\n        console.log(res);\n        alert('Uploaded Successfully.');\n      })\n  }\n}<\/code><\/pre>\n\n\n\n<h4>Step 5 \u2013 Create Upload.php File<\/h4>\n\n\n\n<p>In this step, Create upload.php file and update following code into it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\n   \n    header(\"Access-Control-Allow-Origin: *\");\n    header(\"Access-Control-Allow-Methods: PUT, GET, POST\");\n    header(\"Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept\");\n       \n    $folderPath = \"upload\/\";\n    $postdata = file_get_contents(\"php:\/\/input\");\n    $request = json_decode($postdata);\n       \n    $image_parts = explode(\";base64,\", $request->fileSource);\n       \n    $image_type_aux = explode(\"image\/\", $image_parts&#91;0]);\n       \n    $image_type = $image_type_aux&#91;1];\n       \n    $image_base64 = base64_decode($image_parts&#91;1]);\n       \n    $file = $folderPath . uniqid() . '.png';\n       \n    file_put_contents($file, $image_base64);\n   \n?><\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Note that, the upload.php file code will help you to upload image on server from angular 11 app.<\/p><\/blockquote>\n\n\n\n<h4>Step 6 \u2013 Start Angular App And PHP Server<\/h4>\n\n\n\n<p>In this step, execute the following commands on terminal to start angular app and as well as php server:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ng serve\n\nphp -S localhost:8001<\/code><\/pre>\n\n\n\n<p>As final result, we could have something like this:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/raw.githubusercontent.com\/promosis\/file-upload-with-preview\/master\/public\/file-upload-with-preview-animated.gif\" alt=\"\"\/><\/figure>\n\n\n\n<h5>Reference:<\/h5>\n\n\n\n<p><a href=\"https:\/\/www.tutsmake.com\/\">https:\/\/www.tutsmake.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will learn how to upload image with preview in angular 11 app. As well as, this tutorial will guide us step by step on how to upload image in angular 11. And also use reactive form with formGroup to upload image with preview. Image Upload with Preview in Angular 11 Reactive [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":750,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[37,9],"tags":[177,178,179,176],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/746"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=746"}],"version-history":[{"count":1,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/746\/revisions"}],"predecessor-version":[{"id":748,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/746\/revisions\/748"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/750"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=746"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=746"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=746"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}