【问题标题】:PrimeNG - Sending form data and FileUpload data via button clickPrimeNG - 通过按钮单击发送表单数据和文件上传数据
【发布时间】:2019-02-04 01:13:12
【问题描述】:

在我们的 Angular 项目中,我们有一个包含表单字段和 PrimeNG FileUpload 的表单,我们尝试使用选定的文件发送表单数据。

我们查看了documentation 和网络上的许多示例,但没有一个满足我们的要求(使用保存按钮而不是自动上传或文件上传按钮发送表单和文件)。

我们尝试了以下方法,将每个模型属性附加到文件上传请求中的文件,但我认为必须有一种更聪明的方法,即在 Save 方法(在 .ts 文件中)中将文件附加到模型属性。

HTML:

<p-fileUpload name="files" url="/MyController/Save" 
    (onBeforeSend)="onBeforeSendFile($event)" 
    (onUpload)="onUploadFile($event)" 
    (onError)="onErrorFile($event)" 
    (onBeforeUpload)="onBeforeUploadFoto($event)" 
    multiple="multiple" 
    chooseLabel="Select" 
    uploadLabel="Load" 
    cancelLabel="Cancel">
</p-fileUpload>

.ts:

//code omitted fo brevity

//at here we append model properties to the array in file upload request:
onBeforeUploadFoto(event: any) {
    event.formData.append('id', this.entityId);
    event.formData.append('name', this.entityName);
}

【问题讨论】:

  • @ShanilArjuna 请回复?
  • is (onBeforeSend)="onBeforeSendFile($event)" 是否按预期工作?
  • 不,因为我需要手动调用上传,即在PrimeNG manually invoke FileUpload。但不要将文件数据传递给 ASP.NET MVC 中的控制器。也许它与请求标头等有关我不确定:(
  • 您可以使用 onSelect 读取文件,然后使用fileReader.readAsDataURL 读取数据。如果您需要,我可以发布解决方案
  • @Toolkit 非常感谢您的回复。实际上我解决了这个问题,但如果它准备好了,你可以在这里发布它,这样其他人也会从你的解决方案中受益。问候...

标签: angular typescript file-upload primeng


【解决方案1】:

你可以使用 onSelect 事件:

<p-fileUpload name="files" (onSelect)="dealWithFiles($event)"></p-fileUpload>

在你的组件中:

dealWithFiles(event) {
    files = event.originalEvent.files;
    // Deal with your files
    // e.g  assign it to a variable, and on submit add the variable to your form data
}

如果你想手动上传(通过另一个按钮),然后通过添加隐藏默认上传按钮:

<p-fileUpload name="files" showUploadButton="false" (onSelect)="dealWithFiles($event)"></p-fileUpload>

【讨论】:

    【解决方案2】:

    添加对您的p-fileUpload 的引用,以便您可以从您的Save 方法对其调用upload 方法。

    <p-fileUpload #fileInput name="files" ...
    

    @ViewChild('fileInput') fileInput: FileUpload;
    
    // ...
    
    // save method manually called by clicking on your Save button
    save() {
        if (this.fileInput && this.fileInput.files.length > 0) {
            this.fileInput.upload();
        }
    }
    

    【讨论】:

    • 感谢您的回复。我已经尝试过这种方法,因为我在上面的 PrimeNG 手动调用 FileUpload 页面上提到了我的 cmets。但是,从 service.ts 返回后,文件数据在 Controller (ASP.NET MVC) 中作为 null 传递。知道如何设置 'Content-Type': 'multipart/form-data'?我提供了Cannot set Content-Type in Angular FileUpload control的详细信息。
    猜你喜欢
    • 1970-01-01
    • 2018-11-20
    • 2014-03-01
    • 2016-02-19
    • 2015-05-22
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    相关资源
    最近更新 更多