Angular File Upload

后端 未结 12 1987
名媛妹妹
名媛妹妹 2020-11-22 10:04

I\'m a beginner with Angular, I want to know how to create Angular 5 File upload part, I\'m trying to find any tutorial or doc, but I don\'t see anything a

相关标签:
12条回答
  • 2020-11-22 10:41

    Here is a working example for file upload to api:

    Step 1: HTML Template (file-upload.component.html)

    Define simple input tag of type file. Add a function to (change)-event for handling choosing files.

    <div class="form-group">
        <label for="file">Choose File</label>
        <input type="file"
               id="file"
               (change)="handleFileInput($event.target.files)">
    </div>
    

    Step 2: Upload Handling in TypeScript (file-upload.component.ts)

    Define a default variable for selected file.

    fileToUpload: File = null;
    

    Create function which you use in (change)-event of your file input tag:

    handleFileInput(files: FileList) {
        this.fileToUpload = files.item(0);
    }
    

    If you want to handle multifile selection, than you can iterate through this files array.

    Now create file upload function by calling you file-upload.service:

    uploadFileToActivity() {
        this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
          // do something, if upload success
          }, error => {
            console.log(error);
          });
      }
    

    Step 3: File-Upload Service (file-upload.service.ts)

    By uploading a file via POST-method you should use FormData, because so you can add file to http request.

    postFile(fileToUpload: File): Observable<boolean> {
        const endpoint = 'your-destination-url';
        const formData: FormData = new FormData();
        formData.append('fileKey', fileToUpload, fileToUpload.name);
        return this.httpClient
          .post(endpoint, formData, { headers: yourHeadersConfig })
          .map(() => { return true; })
          .catch((e) => this.handleError(e));
    }
    

    So, This is very simple working example, which I use everyday in my work.

    0 讨论(0)
  • 2020-11-22 10:41
    1. HTML
    
        <div class="form-group">
          <label for="file">Choose File</label><br /> <input type="file" id="file" (change)="uploadFiles($event.target.files)">
        </div>
    
        <button type="button" (click)="RequestUpload()">Ok</button>
    
    
    1. ts File
    public formData = new FormData();
    ReqJson: any = {};
    
    uploadFiles( file ) {
            console.log( 'file', file )
            for ( let i = 0; i < file.length; i++ ) {
                this.formData.append( "file", file[i], file[i]['name'] );
            }
        }
    
    RequestUpload() {
            this.ReqJson["patientId"] = "12"
            this.ReqJson["requesterName"] = "test1"
            this.ReqJson["requestDate"] = "1/1/2019"
            this.ReqJson["location"] = "INDIA"
            this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
                this.http.post( '/Request', this.formData )
                    .subscribe(( ) => {                 
                    });     
        }
    
    1. Backend Spring(java file)
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    @Controller
    public class Request {
        private static String UPLOADED_FOLDER = "c://temp//";
    
        @PostMapping("/Request")
        @ResponseBody
        public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
            System.out.println("Json is" + Info);
            if (file.isEmpty()) {
                return "No file attached";
            }
            try {
                // Get the file and save it somewhere
                byte[] bytes = file.getBytes();
                Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
                Files.write(path, bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "Succuss";
        }
    }
    

    We have to create a folder "temp" in C drive, then this code will print the Json in console and save the uploaded file in the created folder

    0 讨论(0)
  • 2020-11-22 10:44

    Ok, as this thread appears among the first results of google and for other users having the same question, you don't have to reivent the wheel as pointed by trueboroda there is the ng2-file-upload library which simplify this process of uploading a file with angular 6 and 7 all you need to do is:

    Install the latest Angular CLI

    yarn add global @angular/cli
    

    Then install rx-compat for compatibility concern

    npm install rxjs-compat --save
    

    Install ng2-file-upload

    npm install ng2-file-upload --save
    

    Import FileSelectDirective Directive in your module.

    import { FileSelectDirective } from 'ng2-file-upload';
    
    Add it to [declarations] under @NgModule:
    declarations: [ ... FileSelectDirective , ... ]
    

    In your component

    import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
    ...
    
    export class AppComponent implements OnInit {
    
       public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo'});
    }
    

    Template

    <input type="file" name="photo" ng2FileSelect [uploader]="uploader" />
    

    For better understanding you can check this link: How To Upload a File With Angular 6/7

    0 讨论(0)
  • 2020-11-22 10:45

    First, you need to set up HttpClient in your Angular project.

    Open the src/app/app.module.ts file, import HttpClientModule and add it to the imports array of the module as follows:

    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 { }
    

    Next, generate a component:

    $ ng generate component home
    

    Next, generate an upload service:

    $ ng generate service upload
    

    Next, open the src/app/upload.service.ts file as follows:

    import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from  '@angular/common/http';  
    import { map } from  'rxjs/operators';
    
    @Injectable({  
      providedIn: 'root'  
    })  
    export class UploadService { 
        SERVER_URL: string = "https://file.io/";  
        constructor(private httpClient: HttpClient) { }
        public upload(formData) {
    
          return this.httpClient.post<any>(this.SERVER_URL, formData, {  
             reportProgress: true,  
             observe: 'events'  
          });  
       }
    }
    

    Next, open the src/app/home/home.component.ts file, and start by adding the following imports:

    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';
    

    Next, define the fileUpload and files variables and inject UploadService as follows:

    @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) { }
    

    Next, define the uploadFile() method:

    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(`${file.data.name} upload failed.`);  
          })).subscribe((event: any) => {  
            if (typeof (event) === 'object') {  
              console.log(event.body);  
            }  
          });  
      }
    

    Next, define the uploadFiles() method which can be used to upload multiple image files:

    private uploadFiles() {  
        this.fileUpload.nativeElement.value = '';  
        this.files.forEach(file => {  
          this.uploadFile(file);  
        });  
    }
    

    Next, define the onClick() method:

    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();  
    }
    

    Next, we need to create the HTML template of our image upload UI. Open the src/app/home/home.component.html file and add the following content:

    <div [ngStyle]="{'text-align':center; 'margin-top': 100px;}">
       <button mat-button color="primary" (click)="fileUpload.click()">choose file</button>  
       <button mat-button color="warn" (click)="onClick()">Upload</button>  
       <input [hidden]="true" type="file" #fileUpload id="fileUpload" name="fileUpload" multiple="multiple" accept="image/*" />
    </div>
    

    Check out this tutorial and this post

    0 讨论(0)
  • 2020-11-22 10:48

    Try this

    Install

    npm install primeng --save
    

    Import

    import {FileUploadModule} from 'primeng/primeng';
    

    Html

    <p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
        accept="image/*" auto="auto"></p-fileUpload>
    
    0 讨论(0)
  • 2020-11-22 10:50

    In Angular 7/8/9

    Source Link

    Using Bootstrap Form

    <form>
        <div class="form-group">
            <fieldset class="form-group">
    
                <label>Upload Logo</label>
                {{imageError}}
                <div class="custom-file fileInputProfileWrap">
                    <input type="file" (change)="fileChangeEvent($event)" class="fileInputProfile">
                    <div class="img-space">
    
                        <ng-container *ngIf="isImageSaved; else elseTemplate">
                            <img [src]="cardImageBase64" />
                        </ng-container>
                        <ng-template #elseTemplate>
    
                            <img src="./../../assets/placeholder.png" class="img-responsive">
                        </ng-template>
    
                    </div>
    
                </div>
            </fieldset>
        </div>
        <a class="btn btn-danger" (click)="removeImage()" *ngIf="isImageSaved">Remove</a>
    </form>
    

    In Component Class

    fileChangeEvent(fileInput: any) {
        this.imageError = null;
        if (fileInput.target.files && fileInput.target.files[0]) {
            // Size Filter Bytes
            const max_size = 20971520;
            const allowed_types = ['image/png', 'image/jpeg'];
            const max_height = 15200;
            const max_width = 25600;
    
            if (fileInput.target.files[0].size > max_size) {
                this.imageError =
                    'Maximum size allowed is ' + max_size / 1000 + 'Mb';
    
                return false;
            }
    
            if (!_.includes(allowed_types, fileInput.target.files[0].type)) {
                this.imageError = 'Only Images are allowed ( JPG | PNG )';
                return false;
            }
            const reader = new FileReader();
            reader.onload = (e: any) => {
                const image = new Image();
                image.src = e.target.result;
                image.onload = rs => {
                    const img_height = rs.currentTarget['height'];
                    const img_width = rs.currentTarget['width'];
    
                    console.log(img_height, img_width);
    
    
                    if (img_height > max_height && img_width > max_width) {
                        this.imageError =
                            'Maximum dimentions allowed ' +
                            max_height +
                            '*' +
                            max_width +
                            'px';
                        return false;
                    } else {
                        const imgBase64Path = e.target.result;
                        this.cardImageBase64 = imgBase64Path;
                        this.isImageSaved = true;
                        // this.previewImagePath = imgBase64Path;
                    }
                };
            };
    
            reader.readAsDataURL(fileInput.target.files[0]);
        }
    }
    
    removeImage() {
        this.cardImageBase64 = null;
        this.isImageSaved = false;
    }
    
    0 讨论(0)
提交回复
热议问题