角度ng2文件上传问题

时间:2018-06-02 17:42:50

标签: angular angular5 multer ng2-file-upload

我正在尝试上传不同的文件。但问题出现的时候,当我选择一个文件第二次被添加到fileArray时,它就不会被替换。

例如,我为第一个输入选择了一张图片。然后我决定为同一个输入选择不同的图片然后它会被添加到一个文件数组中,所以当我上传它时,上一张图片也会被上传,我不想这样做。

有没有任何解决方案(除了使用单个按钮上传多个文件),这样当我第二次选择文件时,它会被替换而不是添加到文件数组中?

uploadDocument.html文件:

<form (ngSubmit)=f.form.valid && formSubmit() #f="ngForm">

        <input type="file" class="form-control ml-2" name="photo" ng2FileSelect [uploader]="uploader" />
          <input type="file" class="form-control ml-2" name="document1" ng2FileSelect [uploader]="uploader" />
            <input type="file" class="form-control ml-2" name="pic2" ng2FileSelect [uploader]="uploader" />

    <button type="submit" class="btn btn-danger btn-lg btn-fill">Upload</button>

</form>

uploadDocument.component.ts文件:

import { Component, OnInit, Renderer, ElementRef } from '@angular/core';
import { UserService } from '../_services';
import { ActivatedRoute, Router, Params} from '@angular/router';
import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
import { FileSelectDirective } from 'ng2-file-upload';

const URL = 'http://localhost:3002/api/upload';

@Component({
    selector: 'app-uploadDocument',
    templateUrl: './uploadDocument.component.html',
    styleUrls: ['./uploadDocument.component.scss']
})

export class UploadDocument implements OnInit {
    model: any = {};
    mobile: number;
    options: boolean;
    loading = false;
    public uploader:FileUploader = new FileUploader({url: URL});

    constructor(private userService: UserService, private route:ActivatedRoute,private router:Router, private el: ElementRef) { }

    ngOnInit() {


        this.uploader.onBeforeUploadItem = (item)=> {console.log("Item"); console.log(item)};

        this.uploader.onAfterAddingFile = (file)=> { file.withCredentials = false;};

       this.uploader.onCompleteItem = (item:any, response:any, status:any, headers:any) => {
             console.log("ImageUpload:uploaded:", item, status, response);
        };
    }

    formSubmit() {
        this.uploader.uploadAll();
    }

}

3 个答案:

答案 0 :(得分:1)

由于这个原因,我什至失去了几个小时。最后,我做了一个调整来修复它。每当上载新文件时,上载队列都将重置为仅存储最新文件。这是借助库提供的函数的onAfterAddingFile回调完成的。下面是更改后的代码。

uploadDocument.component.ts文件:

import { Component, OnInit, Renderer, ElementRef } from '@angular/core';
import { UserService } from '../_services';
import { ActivatedRoute, Router, Params} from '@angular/router';
import { FileUploader, FileItem } from 'ng2-file-upload';

const URL = 'http://localhost:3002/api/upload';

@Component({
    selector: 'app-uploadDocument',
    templateUrl: './uploadDocument.component.html',
    styleUrls: ['./uploadDocument.component.scss']
})

export class UploadDocument implements OnInit {
    model: any = {};
    mobile: number;
    options: boolean;
    loading = false;
    public uploader:FileUploader = new FileUploader({url: URL});

    constructor(private userService: UserService, private route:ActivatedRoute,private router:Router, private el: ElementRef) { }

    ngOnInit() {

         this.uploader.onAfterAddingFile = (fileItem: FileItem) => this.onAfterAddingFile(fileItem)

    }

    onAfterAddingFile(fileItem: FileItem) {
       let latestFile = this.uploader.queue[this.uploader.queue.length-1]
       this.uploader.queue = []; 
       this.uploader.queue.push(latestFile);
    }

    formSubmit() {
        this.uploader.uploadAll();
    }

}

希望这对您有所帮助!。

答案 1 :(得分:0)

好吧,您可以显示队列并让用户管理(删除)文件。不是最佳选择,但可以使用。

    <p class="files-uploaded" *ngFor="let item of uploader.queue">
      <strong>
        {{ item?.file?.name }} 
        <button type="button" class="btn btn-danger btn-xs"(click)="item.remove()">
          <span class="glyphicon glyphicon-trash"></span> Remove
        </button>
      </strong>
    </p>

答案 2 :(得分:0)

对我来说,前三个输入是必需的,其他三个输入是可选的,所以我这样做了,每个输入将始终仅接受一个文件,如果选择了另一个文件,它将被替换:

import { Component, OnInit, ElementRef } from '@angular/core';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { ApiDomain } from '../url.constants';

const URL = ApiDomain+'/api/upload';

@Component({
    selector: 'app-uploadDocument',
    templateUrl: './uploadDocument.component.html',
    styleUrls: ['./uploadDocument.component.scss']
})

export class UploadDocument implements OnInit {
    model: any = {};
    id: string;
    options: boolean;
    loading = false;
    files = [];
    flag: number = 0;
    formData: FormData;
    filesArray: any;

    constructor(private el: ElementRef, private route: ActivatedRoute, private router: Router, private http: HttpClient) { }

    ngOnInit() {

        this.route.params.subscribe(
            (params: Params) => {
                this.id = params["id"];
                console.log(this.id);
            });

    }

    formSubmit() {
        this.loading = true;
        let inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#tenththmarksheet');
        let inputEl1: HTMLInputElement = this.el.nativeElement.querySelector('#photo');
        let inputEl2: HTMLInputElement = this.el.nativeElement.querySelector('#aadharcard');
        let inputEl3: HTMLInputElement = this.el.nativeElement.querySelector('#caste');
        let inputEl4: HTMLInputElement = this.el.nativeElement.querySelector('#bhamasha');
        let inputEl5: HTMLInputElement = this.el.nativeElement.querySelector('#moolnivas');


        let fileCount: number = inputEl.files.length;
        let fileCount1: number = inputEl1.files.length;
        let fileCount2: number = inputEl2.files.length;
        let fileCount3: number = inputEl3.files.length;
        let fileCount4: number = inputEl4.files.length;
        let fileCount5: number = inputEl5.files.length;

        let formData = new FormData();

        if (fileCount > 0 && fileCount1 > 0 && fileCount2 > 0) {

            formData.append('id', this.id);
            formData.append('tenthmarksheet', inputEl.files.item(0));
            formData.append('photo', inputEl1.files.item(0));
            formData.append('aadhar', inputEl2.files.item(0));

            if (fileCount3 > 0) {
                formData.append('castecertificate', inputEl3.files.item(0));
            }
            if (fileCount4 > 0) {
                formData.append('bhamasha', inputEl4.files.item(0));
            }

            if (fileCount5 > 0) {
                formData.append('moolniwas', inputEl5.files.item(0));
            }

            this.http.post(URL, formData).subscribe(
                (complete) => {
                    this.loading = false;    
                    this.router.navigate(['/thankyou']);
                },
                (error) => {
                    console.log(error);
                    this.loading = false;
                });
        }

    }

}