简体   繁体   中英

Angular 2 File Upload sample

Please could you share a simple file upload sample that conveys the basics of such functionality when using Angular 2?

The research I did (am doing) keeps bubbling up older versions of Angular. At this point all I'm trying to do is load a small image file into a property, or local storage, and have it displayed on the webpage.

I imagine it implies the use of HttpClient however as I'm new to Angular 2 it's challenging to drum up the beginnings of how this works without leaning on a simple sample.

I'm trying this and it's not having the effect I was expecting. It feels like I'm missing an import. This portion is only trying to get the name of the file out, not the image rendered. It appears using [(ngModel)] is not an option, and I must resort to change event to get the selected file.

Component

@Component({
    selector:'home-page'
    ,templateUrl:'./home.page.html'
})
export class HomePageComponent{
    CurrentFile:File;
    public FileChangeEvent(fileInput:any){
        this.CurrentFile = fileInput.target.files[0];
    }
}

html

<div>
    <input type="file" (change)="FileChangeEvent($event)">
    <div *ngIf="CurrentFile">
        <p>{{CurrentFile.name}}</p>
    </div>
</div>

Everything you need there to upload files in Angular 2:

https://github.com/valor-software/ng2-file-upload

After a rough go of it I got what I think can be considered bare basics. There is no attempt to handle things such as when no image is selected, aside from when the page loads and file is unknown.

Component

@Component({
    selector:'home-page'
    ,templateUrl:'./home.page.html'
})
export class HomePageComponent{
    CurrentFile:File;
    ImageSource:string;

    public FileChangeEvent(fileInput:any){
        this.CurrentFile = fileInput.target.files[0];

        let reader = new FileReader();
        reader.onload = () => {
                this.ImageSource = reader.result;
            };
        reader.readAsDataURL(this.CurrentFile);
    }
}

HTML

<div>
    <input type="file" (change)="FileChangeEvent($event)">
    <div *ngIf="CurrentFile">
        <img [src]="ImageSource">
    </div>
</div>

You can use this answer to upload the file to your server:

https://stackoverflow.com/a/40216616/5413117

You can then for example upload it to azure and show the image through the azure storage link.

If you want to get rid of using the file changed event, although it works, you can write a control value accessor for file inputs, explained here:

https://stackoverflow.com/a/41938495/5413117

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM