ng2-file-upload:如何更改文件上传的表单数据名称

时间:2019-04-01 14:04:32

标签: angular typescript angular7 form-data ng2-file-upload

我目前正在使用此代码上传文件(Angular 2 +):

upload() {
  let inputEl: HTMLInputElement = this.inputEl.nativeElement;
  let fileCount: number = inputEl.files.length;
  let formData = new FormData();
  if (fileCount > 0) { // a file was selected
      for (let i = 0; i < fileCount; i++) {
          formData.append('files', inputEl.files.item(i));
      }
      this.http.post(mySecretUrl, formData, {observe: 'response'}).subscribe(err => this.handleError(err), resp => {
        console.log(resp);
      });
  }
}

使用html:

<input #fileInput type="file" [multiple]="true" id="file-upload" size="60">

这工作正常,但由于该软件包附带的所有其他功能,我想使用ng2-file-upload。

当我输入ng2-file-upload的代码并尝试上传时,出现500错误。我100%肯定问题是键名'files',您可以在旧代码的这一行中找到它:

formData.append('files', inputEl.files.item(i));

使用ng2-file-upload时,如何将表单数据键名添加/更改为“文件”?

这是我的ng2-file-upload代码:

    function readBase64(file): Promise<any> {
    var reader  = new FileReader();
    var future = new Promise((resolve, reject) => {
      reader.addEventListener("load", function () {
        resolve(reader.result);
      }, false);

      reader.addEventListener("error", function (event) {
        reject(event);
      }, false);

      reader.readAsDataURL(file);
    });
    return future;


    }

    const URL = 'mySecretUrl';

    private uploader:FileUploader = new FileUploader({
      url: URL, 
      disableMultipart:true
    });

    public hasBaseDropZoneOver:boolean = false;
    fileObject: any;

    public fileOverBase(e:any):void {
      this.hasBaseDropZoneOver = e; 
    }

    public onFileSelected(event: EventEmitter<File[]>) {
      const file: File = event[0];

      console.log(file);

      readBase64(file)
        .then(function(data) {
        console.log(data);
      })
    }

还有html:

<input type="file" ng2FileSelect [uploader]="uploader" multiple (onFileSelected)="onFileSelected($event)"  />

编辑:

我想我的问题的答案是:

    public uploader: FileUploader = new FileUploader({
        ...
        itemAlias: 'files'
        ...
    })

...但是当我尝试上传时,我仍然收到500(内部服务器错误)...

1 个答案:

答案 0 :(得分:-2)

如果服务器端出现问题,通常会出现

500错误。尝试查看您的API端点配置是否正确。