使用Primeng上传组件上传文件

时间:2018-09-12 10:00:21

标签: javascript angular typescript primeng

我将使用upload component

将文件上传到Angular中

这是我的HTML:

<p-fileUpload mode="basic" name="demo[]" customUpload="true" accept="image/*" maxFileSize="1000000"  (uploadHandler)="upload($event)"></p-fileUpload>

在我的 ts 中打印参数值

upload(event) {
  console.log(event)
}

我只获得元数据,而没有blob内容

{"files":[{"objectURL":{"changingThisBreaksApplicationSecurity":"blob:https://prime-ng-file-uploading.stackblitz.io/d429e761-c391-45fa-8628-39b603e25225"}}]}

我还将获得要通过API发送到服务器的文件内容

Here's a stackblitz demo

2 个答案:

答案 0 :(得分:4)

在官方文档中,您有一个示例:

export class FileUploadDemo {
  uploadedFiles: any[] = [];
  constructor(private messageService: MessageService) {}
  onUpload(event) {
    for (let file of event.files) {
      this.uploadedFiles.push(file);
    }
    this.messageService.add({
      severity: 'info',
      summary: 'File Uploaded',
      detail: ''
    });
  }
}

使用primeNG时,我是这样做的(仅上传1个文件):

  

HTML

 <p-fileUpload name="myfile[]" customUpload="true" multiple="multiple" (uploadHandler)="onUpload($event)" accept="application/pdf"></p-fileUpload>
  

component.ts

export class AlteracionFormComponent {
  uplo: File;
  constructor(private fileService: FileUploadClientService) {}
  onUpload(event) {
    for (let file of event.files) {
      this.uplo = file;
    }
    this.uploadFileToActivity();
  }
  uploadFileToActivity() {
    this.fileService.postFile(this.uplo).subscribe(data => {
      alert('Success');
    }, error => {
      console.log(error);
    });
  }
}

还有我的服务(在Angular中)

  

service.ts

  postFile(id_alteracion: string, filesToUpload: FileUploadModel[], catalogacion: any): Observable<any> {
    let url = urlAPIAlteraciones + '/';
    url += id_alteracion + '/documentos';

    const formData: FormData = new FormData();

    formData.append('json', JSON.stringify(catalogacion));

    for (let file of filesToUpload) {
      formData.append('documento', file.data, file.data.name);
    }

    console.log(formData);

    let headers = new HttpHeaders();

    return this._http.post(url, formData, { headers: headers });
  }

希望有帮助

答案 1 :(得分:0)

我正在尝试使用标准的PrimeNG方法一次上传多个文件。

<p-fileUpload name="myfile[]" [url]="MyApiUrl" multiple="multiple"></p-fileUpload>

在我的ApiController中,我得到以下信息:

public List<FileModel> Post()
{
    var files = HttpContext.Current.Request.Files;
    var result = new List<FileModel>();

    if (files.Count > 0)
    {
        Guid guid = Guid.NewGuid();
        var path = System.IO.Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["UploadFileLocation"], guid.ToString() + "/");
        System.Web.HttpContext.Current.Session["guid"] = guid;

        if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); }

        foreach (string fileName in files.AllKeys)
        {
            var file = files[fileName];
            var filePath = path + file.FileName;
            file.SaveAs(filePath);
            result.Add(_data.InsertFile(FileModel.Create(path, file.FileName)));
        }
    }
    return result;
}

我遇到的问题是var file = files[fileName]中的“ fileName”始终等于上载的文件组中的第一个文件。我不知道这是HttpContext.Current.Request.Files还是PrimeNG错误的问题。有没有人遇到过这类问题?

之所以这样做是因为我想将guid存储在我的会话中,并在以后提交表单时获取它...