【问题标题】:Angular 8 With Web API File UploadAngular 8 与 Web API 文件上传
【发布时间】:2020-01-28 22:12:43
【问题描述】:

我正在尝试使用带有 asp.net web api 核心的 Angular 8 上传文件,但我没有在服务器上获取文件并且出现此错误。

“无法创建 Microsoft.AspNetCore.Http.IFormFile 类型的实例。类型是接口或抽象类,无法实例化。路径 'patientImage',第 1 行,位置 367。”

我的控制器方法是

[HttpPost]
[Route("CreatePatient")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Patient))]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Post([FromBody] PatientViewModel model)
{
    (Patient, ServiceResponseMessage) newPatient = await PatientServices.CreateNewPatient(model);

    if (newPatient.Item2.Status == ResponseStatus.Failed)
    {
        return BadRequest(newPatient.Item2.Message);
    }
    return Ok(newPatient.Item1);
}

我的班级的一部分是

public class PatientViewModel {
    public IFormFile PatientImage { get; set };
    public string Comment { get; set; }
}

我的 Html 文件是

<h5 class="sub-title">Please Upload Your Image</h5>
<div class="ui-fileupload">
    <p-fileUpload name="myFile[]" (onBeforeSend)="onBeforeSend($event)" enctype="multipart/form-data"
        accept="application/msword,application/pdf, image/*" [showUploadButton]="togglePatientImageUploadButtons"
        [showCancelButton]="togglePatientImageUploadButtons" customUpload="true"
        (onSelect)="showAtView($event, 'patientImage')" (uploadHandler)="onUpload($event, 'patientImage');"
        maxFileSize="50000000">
        <ng-template pTemplate type="content">
            <ul *ngIf="uploadedPatientImage.length">
                <li *ngFor="let file of uploadedPatientImage">{{file.name}} - {{file.size}} bytes</li>
            </ul>
        </ng-template>
    </p-fileUpload>
    <p-messages [(value)]="patientImageError"></p-messages>
</div>

我的 Angular 2 组件方法是方法

onUpload(event, type) {
    if (event.files.length == 0) {
        this.toastr.error("No file selected.");
        return;
    }

    var fileToUpload = event.files[0];
    let formData: FormData = new FormData();
    // input.append("file", fileToUpload);


    if (type == "patientImage") {
        formData.append('patientImage', fileToUpload, fileToUpload.name);
        this.patientInfo.patientImage = formData.get('patientImage');
        this.toastr.success("Uploaded Successfully", '');

    }

    else if (type == "civilId") {
        formData.append('uploadCivilId', fileToUpload, fileToUpload.name);
        this.patientInfo.civilIdPhotoCopy = formData.get('uploadCivilId');
        this.toastr.success("Uploaded Successfully", '');

    }
    else if (type == "passbortImage") {
        formData.append('uploadPassportPhotoCopy', fileToUpload, fileToUpload.name);
        this.patientInfo.passportPhotoCopy = formData.get('uploadPassportPhotoCopy');
        this.toastr.success("Uploaded Successfully", '');
    }
}

【问题讨论】:

    标签: angular asp.net-core asp.net-core-webapi


    【解决方案1】:

    ASP.Net 核心控制器代码:

    [HttpPost("files", Name = "UploadFile")]
    [Route("[action]/{FileName}")]
    public async Task<IActionResult> UploadFile(string FileName, List<IFormFile> files)
    { 
    try
    {foreach (var formFile in files)
    {
    if (formFile.Length > 0)
    {
    using (var stream = new FileStream("PathToExportTo+FileName", FileMode.Create))
    {
    await formFile.CopyToAsync(stream);
    }
    }
    }
    return Ok();
    }
    catch (Exception ex)
    {
    //no actual error handling
    return Ok();
    }
    

    HTML:

    <label for=FileUploader ><input id=FileUploader type="file" multiple="false" (change)="upload($event.target.files)" /></label>
    

    组件代码:

    upload(files: File[]) {
        this._sharedService.UploadFile(files, "FileName");
    

    服务代码:

      UploadFile(files: File[], FileName) {
        var formData = new FormData();
        Array.from(files).forEach(f => formData.append("files", f));
        this.http
          .post("PathToAPI" + FileName, formData)
          .subscribe(event => {});
      }
    

    完全有可能有其他方法来实现这一点,但这是我当前的代码工作版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-27
      • 2017-11-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2020-06-09
      • 2017-10-11
      • 1970-01-01
      相关资源
      最近更新 更多