Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to upload files in Angular

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to upload files in Angular". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

What is a horn?

Angular is a development platform and framework that you can use to create single-page applications in JavaScript (JS) or TypeScript (TS). The framework is written in TS and implemented through libraries that you can import into your project.

The basic structure of Angular is based on NgModules, that is, the collection of components that organize successful energy sets. These modules enable you to define Angular applications and integrate various components. Each application you create in Angular has a root module that supports booting, as well as any functional modules you need.

There are components within each module. These components define the views that can be used in your application. A view is a set of screen elements to which code can be applied. In addition, components include services. Services are classes that provide functionality and enable you to create efficient modular applications.

When you use components and internal services, you rely on metadata to define types and usage. Metadata associates components with view templates and combines HTML with Angular instructions and tags. This allows you to modify the HTML before rendering. Metadata is also the way Angular provides services through dependency injection.

Angular component for file upload

In Angular, you can use multiple components to manually upload files. Depending on how you want to use upload, you may need to modify your use of these methods, or you can simply use a pre-built file upload method. For example, if you are using digital asset management tools, many solutions provide methods that you can easily add.

The following are common elements for completing file uploads using Angular.

Form data

FormData is an object that can be used to store key-value pairs. It enables you to build objects that are aligned to HTML forms. This feature allows you to send data, such as file uploads, to REST API endpoints through the HTTP client library or XMLHttpRequest interface.

To create a FormData object, you can use the following:

Java:

Const formData = new FormData ()

This method enables you to add key values directly or collect data from existing HTML forms.

HttpClient module

HttpClientModule is a module that contains API that you can use to send and retrieve application data from a HTTP server. It is based on the XMLHttpRequest interface. It includes features that enable you to avoid extracting JSON data, modify request headers using interceptors, and add interceptors to provider headers.

You can import this module by adding the following to the JSON package file:

Java:

Import {HttpClientModule} from'@ angular/common/http'; reaction form

Reactive forms enable you to use a model-driven approach to handling form input with varying values. Using these forms, you can use multiple controls in a form group, validate form values, and build forms that can modify controls dynamically. This is possible because form data is returned as an immutable, observable stream, not as mutable data points as template-driven forms.

You can import this module using the following command:

Java:

Import {ReactiveFormsModule} from'@ angular/forms';@NgModule ({imports: [/ / other imports... ReactiveFormsModule],}) export class AppModule {} how to upload files in Angular 9: quick tutorials

If you are going to try to use the Angular application for file upload, you can try the following tutorial using FormData and HttpClientModule. This tutorial is adapted from a longer tutorial by Ahmed Bouchefra.

To start this tutorial, you need to have the following:

File sharing services such as file.io or Dropbox

Development environment for Node.js 8.9 + and npm 5.5.1 +

Corner CLI you can install it globally using npm install-g @ angular/cli in the system CLI

1. Create a new application and start the development server

First, you need to create an application to handle uploads. You can create a new application by entering the following in the terminal:

Java:

Ng new {Application name}

When creating this, you need to specify whether to add Angular routing (Yes) and your stylesheet format (CSS).

Next, you need to start the local development server from the terminal:

Java:

Cd {Application name} ng serve

This starts a server and returns the local host address. Open the returned site in a browser to view your application.

two。 Set up HttpClientModule

Initialize your project through Angular CLI and import HttpClientModule. To do this, you need to open the src/app/app.module.ts file. You can do this using the following methods:

Java:

Import {BrowserModule} from'@ angular/platform-browser';import {NgModule} from'@ angular/core';import {AppRoutingModule} from'. / app-routing.module';import {AppComponent} from'. / app.component';import {HttpClientModule} from'@ angular/common/http';@NgModule ({declarations: [AppComponent,], imports: [BrowserModule, AppRoutingModule, HttpClientModule], providers: [], bootstrap: [AppComponent]}) export class AppModule {} 3. Add control components and user interface

To add a UI control component, you need to create a home and about component. You can add these to the terminal using the following command:

Java:

Cd ~ / angular-upload-exampleng generate component homeng generate component about

To complete UI, you can create components manually or use other modules, such as Angular Material. Whichever method you choose, you at least need to define your uploadFile () method and provide buttons or submit methods for your users.

Then you need to add the components to the router in the following ways: the src/app/app-routing.module.ts file.

Java:

Import {NgModule} from'@ angular/core';import {Routes, RouterModule} from'@ angular/router';import {HomeComponent} from'. / home/home.component';import {AboutComponent} from'. / about/about.component';const routes: Routes = [{path:'', redirectTo: 'home', pathMatch:' full'}, {path: 'home', component: HomeComponent}, {path:' about', component: AboutComponent},] NgModule ({imports: [RouterModule.forRoot (routes)], exports: [RouterModule]}) export class AppRoutingModule {} 4. Create your upload service

First, you need to create your service with the following:

Java:

Ng generate service upload

In the src/app/upload.service.ts file, add your import and inject your HTTP client:

Java:

Import {HttpClient, HttpEvent, HttpErrorResponse, HttpEventType} from'@ angular/common/http';@Injectable ({providedIn: 'root'}) export class UploadService {SERVER_URL: string = "{Server URL}"; constructor (private httpClient: HttpClient) {}

You also need to add your upload method, which allows you to call the post method and send the data to your upload server.

Java:

Public upload (formData) {return this.httpClient.post (this.SERVER_URL, formData, {reportProgress: true, observe: 'events'});} 5. Define your upload method

After creating the service, you need to define the upload method and add error handling. If you prefer, you can also add a progress bar element here and change the UI style.

In the src/app/home/home.component.ts file, add your import.

Java:

Import {Component, OnInit, ViewChild, ElementRef} from'@ angular/core';import {HttpEventType, HttpErrorResponse} from'@ angular/common/http';import {of} from 'rxjs';import {catchError, map} from' rxjs/operators';import {UploadService} from'. / upload.service' @ Component ({selector: 'app-home', templateUrl:'. / home.component.html', styleUrls: ['. / home.component.css']}) export class HomeComponent implements OnInit {@ ViewChild ("fileUpload", {static: false}) fileUpload: ElementRef;files = []; constructor (private uploadService: UploadService) {}

Now you can define your methods and variables and inject your upload service.

Java:

UploadFile (file) {const formData = new FormData (); formData.append ('file', file.data); file.inProgress = true; this.uploadService.upload (formData). Pipe (map (event = > {switch (event.type) {case HttpEventType.UploadProgress: file.progress = Math.round (event.loaded * 100 / event.total); break Case HttpEventType.Response: return event;}}), catchError ((error: HttpErrorResponse) = > {file.inProgress = false; return of (`Upload failed: ${file.data.name} `);}) .subscribe ((event: any) = > {if (typeof (event) = 'object') {console.log (event.body)) });}

To enable users to submit files, you should also define an onClick () method associated with the submit button.

Java:

OnClick () {const fileUpload = this.fileUpload.nativeElement;fileUpload.onchange = () = > {for (let index = 0; index < fileUpload.files.length; index++) {const file = fileUpload.files [index]; this.files.push ({data: file, inProgress: false, progress: 0});} this.uploadFiles ();}; fileUpload.click ();}

You can now test your application through your local browser to make sure it works as expected.

This is the end of "how to upload files in Angular". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report