Repository: LukasMarx/angular-file-upload Branch: master Commit: 01864cfa0843 Files: 41 Total size: 28.5 KB Directory structure: gitextract_w0g4_mjq/ ├── LICENSE ├── README.md ├── client/ │ ├── .editorconfig │ ├── .gitignore │ ├── README.md │ ├── angular.json │ ├── browserslist │ ├── e2e/ │ │ ├── src/ │ │ │ ├── app.e2e-spec.ts │ │ │ └── app.po.ts │ │ └── tsconfig.json │ ├── karma.conf.js │ ├── package.json │ ├── src/ │ │ ├── app/ │ │ │ ├── app.component.html │ │ │ ├── app.component.scss │ │ │ ├── app.component.spec.ts │ │ │ ├── app.component.ts │ │ │ ├── app.module.ts │ │ │ └── upload/ │ │ │ ├── dialog/ │ │ │ │ ├── dialog.component.html │ │ │ │ ├── dialog.component.scss │ │ │ │ └── dialog.component.ts │ │ │ ├── upload.component.html │ │ │ ├── upload.component.scss │ │ │ ├── upload.component.ts │ │ │ ├── upload.module.ts │ │ │ └── upload.service.ts │ │ ├── assets/ │ │ │ └── .gitkeep │ │ ├── environments/ │ │ │ ├── environment.prod.ts │ │ │ └── environment.ts │ │ ├── index.html │ │ ├── main.ts │ │ ├── polyfills.ts │ │ ├── styles.scss │ │ └── test.ts │ ├── tsconfig.app.json │ ├── tsconfig.json │ ├── tsconfig.spec.json │ └── tslint.json └── server/ ├── .gitignore ├── package.json ├── server.js └── upload.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2019 Lukas Marx Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ ![image](https://raw.githubusercontent.com/LukasMarx/angular-file-upload/master/angular-file-upload-component.png) # Creating a File Upload Component in Angular ## Angular version: 8.0.0 Creating file-upload components can be quite hard. Not only because you need to deal with files in JavaScript. Also, because you need an API to test against before you can actually start coding. In this tutorial, we will learn how to do both. First, we will create a simple express server with just one route to accept file uploads. Afterward, we will create an angular application from scratch and build a beautiful file-upload component using the angular material ui-component-library. Here is what the final result will look like: ![image](https://raw.githubusercontent.com/LukasMarx/angular-file-upload/master/angular-file-upload-result.png) Ready? Let's start coding! [Read the full article at malcoded.com!](https://malcoded.com/posts/angular-file-upload-component-with-express) ================================================ FILE: client/.editorconfig ================================================ # Editor configuration, see https://editorconfig.org root = true [*] charset = utf-8 indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true [*.md] max_line_length = off trim_trailing_whitespace = false ================================================ FILE: client/.gitignore ================================================ # See http://help.github.com/ignore-files/ for more about ignoring files. # compiled output /dist /dist-server /tmp /out-tsc # Only exists if Bazel was run /bazel-out # dependencies /node_modules # profiling files chrome-profiler-events.json speed-measure-plugin.json # IDEs and editors /.idea .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # IDE - VSCode .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json .history/* # misc /.sass-cache /connect.lock /coverage /libpeerconnection.log npm-debug.log yarn-error.log testem.log /typings package-look.json # e2e /e2e/*.js /e2e/*.map # System Files .DS_Store Thumbs.db ================================================ FILE: client/README.md ================================================ # FileUploader This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.0.1. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. ================================================ FILE: client/angular.json ================================================ { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "file-uploader": { "projectType": "application", "schematics": { "@schematics/angular:component": { "style": "scss" } }, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/file-uploader", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.scss" ], "scripts": [] }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "aot": true, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "budgets": [ { "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" } ] } } }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "file-uploader:build" }, "configurations": { "production": { "browserTarget": "file-uploader:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "file-uploader:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.spec.json", "karmaConfig": "karma.conf.js", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.scss" ], "scripts": [] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": [ "tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json" ], "exclude": [ "**/node_modules/**" ] } }, "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "file-uploader:serve" }, "configurations": { "production": { "devServerTarget": "file-uploader:serve:production" } } } } }}, "defaultProject": "file-uploader" } ================================================ FILE: client/browserslist ================================================ # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. # For additional information regarding the format and rule options, please see: # https://github.com/browserslist/browserslist#queries # You can see what browsers were selected by your queries by running: # npx browserslist > 0.5% last 2 versions Firefox ESR not dead not IE 9-11 # For IE 9-11 support, remove 'not'. ================================================ FILE: client/e2e/src/app.e2e-spec.ts ================================================ import { AppPage } from './app.po'; import { browser, logging } from 'protractor'; describe('workspace-project App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getTitleText()).toEqual('Welcome to file-uploader!'); }); afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, } as logging.Entry)); }); }); ================================================ FILE: client/e2e/src/app.po.ts ================================================ import { browser, by, element } from 'protractor'; export class AppPage { navigateTo() { return browser.get(browser.baseUrl) as Promise; } getTitleText() { return element(by.css('app-root h1')).getText() as Promise; } } ================================================ FILE: client/e2e/tsconfig.json ================================================ { "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/e2e", "module": "commonjs", "target": "es5", "types": [ "jasmine", "jasminewd2", "node" ] } } ================================================ FILE: client/karma.conf.js ================================================ // Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, './coverage/file-uploader'), reports: ['html', 'lcovonly', 'text-summary'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true }); }; ================================================ FILE: client/package.json ================================================ { "name": "file-uploader", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build --prod", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "8.0.0", "@angular/cdk": "8.0.0", "@angular/common": "8.0.0", "@angular/compiler": "8.0.0", "@angular/core": "8.0.0", "@angular/flex-layout": "8.0.0-beta.26", "@angular/forms": "8.0.0", "@angular/http": "7.2.15", "@angular/material": "8.0.0", "@angular/platform-browser": "8.0.0", "@angular/platform-browser-dynamic": "8.0.0", "@angular/router": "8.0.0", "core-js": "3.1.3", "rxjs": "6.5.2", "tslib": "1.9.3", "zone.js": "0.9.1" }, "devDependencies": { "@angular-devkit/build-angular": "0.800.1", "@angular/cli": "8.0.1", "@angular/compiler-cli": "8.0.0", "@angular/language-service": "8.0.0", "@types/jasmine": "3.3.13", "@types/jasminewd2": "2.0.6", "@types/node": "12.0.4", "codelyzer": "5.0.1", "jasmine-core": "3.4.0", "jasmine-spec-reporter": "4.2.1", "karma": "4.1.0", "karma-chrome-launcher": "2.2.0", "karma-coverage-istanbul-reporter": "2.0.5", "karma-jasmine": "2.0.1", "karma-jasmine-html-reporter": "1.4.2", "protractor": "5.4.2", "ts-node": "8.2.0", "tslint": "5.17.0", "typescript": "3.4.5" } } ================================================ FILE: client/src/app/app.component.html ================================================ ================================================ FILE: client/src/app/app.component.scss ================================================ ================================================ FILE: client/src/app/app.component.spec.ts ================================================ import { TestBed, async } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], }).compileComponents(); })); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); it(`should have as title 'ng8'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('ng8'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng8!'); }); }); ================================================ FILE: client/src/app/app.component.ts ================================================ import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { } ================================================ FILE: client/src/app/app.module.ts ================================================ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { UploadModule } from './upload/upload.module'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, UploadModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } ================================================ FILE: client/src/app/upload/dialog/dialog.component.html ================================================

Upload Files

{{file.name}}

================================================ FILE: client/src/app/upload/dialog/dialog.component.scss ================================================ .add-files-btn { float: right; } :host { height: 100%; display: flex; flex: 1; flex-direction: column; } .actions { justify-content: flex-end; } .container { height: 100%; } ================================================ FILE: client/src/app/upload/dialog/dialog.component.ts ================================================ import { Component, OnInit, ViewChild } from '@angular/core'; import { MatDialogRef } from '@angular/material'; import { UploadService } from '../upload.service'; import { forkJoin } from 'rxjs'; @Component({ selector: 'app-dialog', templateUrl: './dialog.component.html', styleUrls: ['./dialog.component.scss'] }) export class DialogComponent implements OnInit { @ViewChild('file', { static: false }) file; public files: Set = new Set(); constructor(public dialogRef: MatDialogRef, public uploadService: UploadService) { } ngOnInit() { } progress; canBeClosed = true; primaryButtonText = 'Upload'; showCancelButton = true; uploading = false; uploadSuccessful = false; onFilesAdded() { const files: { [key: string]: File } = this.file.nativeElement.files; for (let key in files) { if (!isNaN(parseInt(key))) { this.files.add(files[key]); } } } addFiles() { this.file.nativeElement.click(); } closeDialog() { // if everything was uploaded already, just close the dialog if (this.uploadSuccessful) { return this.dialogRef.close(); } // set the component state to "uploading" this.uploading = true; // start the upload and save the progress map this.progress = this.uploadService.upload(this.files); console.log(this.progress); for (const key in this.progress) { this.progress[key].progress.subscribe(val => console.log(val)); } // convert the progress map into an array let allProgressObservables = []; for (let key in this.progress) { allProgressObservables.push(this.progress[key].progress); } // Adjust the state variables // The OK-button should have the text "Finish" now this.primaryButtonText = 'Finish'; // The dialog should not be closed while uploading this.canBeClosed = false; this.dialogRef.disableClose = true; // Hide the cancel-button this.showCancelButton = false; // When all progress-observables are completed... forkJoin(allProgressObservables).subscribe(end => { // ... the dialog can be closed again... this.canBeClosed = true; this.dialogRef.disableClose = false; // ... the upload was successful... this.uploadSuccessful = true; // ... and the component is no longer uploading this.uploading = false; }); } } ================================================ FILE: client/src/app/upload/upload.component.html ================================================ ================================================ FILE: client/src/app/upload/upload.component.scss ================================================ ================================================ FILE: client/src/app/upload/upload.component.ts ================================================ import { Component } from '@angular/core'; import { MatDialog } from '@angular/material'; import { DialogComponent } from './dialog/dialog.component'; import { UploadService } from './upload.service'; @Component({ selector: 'app-upload', templateUrl: './upload.component.html', styleUrls: ['./upload.component.scss'] }) export class UploadComponent { constructor(public dialog: MatDialog, public uploadService: UploadService) { } public openUploadDialog() { let dialogRef = this.dialog.open(DialogComponent, { width: '50%', height: '50%' }); } } ================================================ FILE: client/src/app/upload/upload.module.ts ================================================ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { UploadComponent } from './upload.component'; import { MatButtonModule, MatDialogModule, MatListModule, MatProgressBarModule } from '@angular/material'; import { DialogComponent } from './dialog/dialog.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FlexLayoutModule } from '@angular/flex-layout'; import { UploadService } from './upload.service'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [CommonModule, MatButtonModule, MatDialogModule, MatListModule, FlexLayoutModule, HttpClientModule, BrowserAnimationsModule, MatProgressBarModule], declarations: [UploadComponent, DialogComponent], exports: [UploadComponent], entryComponents: [DialogComponent], // Add the DialogComponent as entry component providers: [UploadService] }) export class UploadModule {} ================================================ FILE: client/src/app/upload/upload.service.ts ================================================ import { Injectable } from '@angular/core'; import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http'; import { Subject, Observable } from 'rxjs'; const url = 'http://localhost:3000/upload'; @Injectable() export class UploadService { constructor(private http: HttpClient) { } public upload( files: Set ): { [key: string]: { progress: Observable } } { // this will be the our resulting map const status: { [key: string]: { progress: Observable } } = {}; files.forEach(file => { // create a new multipart-form for every file const formData: FormData = new FormData(); formData.append('file', file, file.name); // create a http-post request and pass the form // tell it to report the upload progress const req = new HttpRequest('POST', url, formData, { reportProgress: true }); // create a new progress-subject for every file const progress = new Subject(); // send the http-request and subscribe for progress-updates const startTime = new Date().getTime(); this.http.request(req).subscribe(event => { if (event.type === HttpEventType.UploadProgress) { // calculate the progress percentage const percentDone = Math.round((100 * event.loaded) / event.total); // pass the percentage into the progress-stream progress.next(percentDone); } else if (event instanceof HttpResponse) { // Close the progress-stream if we get an answer form the API // The upload is complete progress.complete(); } }); // Save every progress-observable in a map of all observables status[file.name] = { progress: progress.asObservable() }; }); // return the map of progress.observables return status; } } ================================================ FILE: client/src/assets/.gitkeep ================================================ ================================================ FILE: client/src/environments/environment.prod.ts ================================================ export const environment = { production: true }; ================================================ FILE: client/src/environments/environment.ts ================================================ // This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: false }; /* * For easier debugging in development mode, you can import the following file * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. * * This import should be commented out in production mode because it will have a negative impact * on performance if an error is thrown. */ // import 'zone.js/dist/zone-error'; // Included with Angular CLI. ================================================ FILE: client/src/index.html ================================================ FileUploader ================================================ FILE: client/src/main.ts ================================================ import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err)); ================================================ FILE: client/src/polyfills.ts ================================================ /** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. * * Learn more in https://angular.io/guide/browser-support */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** IE10 and IE11 requires the following for NgClass support on SVG elements */ // import 'classlist.js'; // Run `npm install --save classlist.js`. /** * Web Animations `@angular/platform-browser/animations` * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). */ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. /** * By default, zone.js will patch all possible macroTask and DomEvents * user can disable parts of macroTask/DomEvents patch by setting following flags * because those flags need to be set before `zone.js` being loaded, and webpack * will put import in the top of bundle, so user need to create a separate file * in this directory (for example: zone-flags.ts), and put the following flags * into that file, and then add the following code before importing zone.js. * import './zone-flags.ts'; * * The flags allowed in zone-flags.ts are listed here. * * The following flags will work for all browsers. * * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames * * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js * with the following flag, it will bypass `zone.js` patch for IE/Edge * * (window as any).__Zone_enable_cross_context_check = true; * */ /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */ ================================================ FILE: client/src/styles.scss ================================================ /* You can add global styles to this file, and also import other style files */ @import '~@angular/material/prebuilt-themes/indigo-pink.css'; ================================================ FILE: client/src/test.ts ================================================ // This file is required by karma.conf.js and loads recursively all the .spec and framework files import 'zone.js/dist/zone-testing'; import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; declare const require: any; // First, initialize the Angular testing environment. getTestBed().initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting() ); // Then we find all the tests. const context = require.context('./', true, /\.spec\.ts$/); // And load the modules. context.keys().map(context); ================================================ FILE: client/tsconfig.app.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/app", "types": [] }, "include": [ "src/**/*.ts" ], "exclude": [ "src/test.ts", "src/**/*.spec.ts" ] } ================================================ FILE: client/tsconfig.json ================================================ { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "module": "esnext", "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "importHelpers": true, "target": "es2015", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2018", "dom" ] } } ================================================ FILE: client/tsconfig.spec.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": [ "jasmine", "node" ] }, "files": [ "src/test.ts", "src/polyfills.ts" ], "include": [ "src/**/*.spec.ts", "src/**/*.d.ts" ] } ================================================ FILE: client/tslint.json ================================================ { "extends": "tslint:recommended", "rules": { "array-type": false, "arrow-parens": false, "deprecation": { "severity": "warn" }, "component-class-suffix": true, "contextual-lifecycle": true, "directive-class-suffix": true, "directive-selector": [ true, "attribute", "app", "camelCase" ], "component-selector": [ true, "element", "app", "kebab-case" ], "import-blacklist": [ true, "rxjs/Rx" ], "interface-name": false, "max-classes-per-file": false, "max-line-length": [ true, 140 ], "member-access": false, "member-ordering": [ true, { "order": [ "static-field", "instance-field", "static-method", "instance-method" ] } ], "no-consecutive-blank-lines": false, "no-console": [ true, "debug", "info", "time", "timeEnd", "trace" ], "no-empty": false, "no-inferrable-types": [ true, "ignore-params" ], "no-non-null-assertion": true, "no-redundant-jsdoc": true, "no-switch-case-fall-through": true, "no-use-before-declare": true, "no-var-requires": false, "object-literal-key-quotes": [ true, "as-needed" ], "object-literal-sort-keys": false, "ordered-imports": false, "quotemark": [ true, "single" ], "trailing-comma": false, "no-conflicting-lifecycle": true, "no-host-metadata-property": true, "no-input-rename": true, "no-inputs-metadata-property": true, "no-output-native": true, "no-output-on-prefix": true, "no-output-rename": true, "no-outputs-metadata-property": true, "template-banana-in-box": true, "template-no-negated-async": true, "use-lifecycle-interface": true, "use-pipe-transform-interface": true }, "rulesDirectory": [ "codelyzer" ] } ================================================ FILE: server/.gitignore ================================================ node_modules ================================================ FILE: server/package.json ================================================ { "name": "image-upload-tutorial-example", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "cors": "^2.8.5", "express": "^4.17.1", "formidable": "^1.2.1" } } ================================================ FILE: server/server.js ================================================ const express = require('express'); const upload = require('./upload'); const cors = require('cors'); const server = express(); var corsOptions = { origin: '*', optionsSuccessStatus: 200 }; server.use(cors(corsOptions)); server.post('/upload', upload); server.listen(3000, () => { console.log('Server started!'); }); ================================================ FILE: server/upload.js ================================================ const IncomingForm = require('formidable').IncomingForm; const fs = require('fs'); module.exports = function upload(req, res) { const form = new IncomingForm(); form.on('file', (field, file) => { // Do something with the file // e.g. save it to the database // you can access it using file.path console.log('file', file.name); const readStream = fs.createReadStream(file.path); }); form.on('end', () => { res.json(); }); form.parse(req); };