带有Web API文件上传的Angular 8

时间:2019-09-29 09:26:53

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

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

  

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

我的控制器方法是

<?php

namespace [vendor_name]\[module_name]\Controller\Adminhtml\[Controller_name];

use Magento\Framework\App\Filesystem\DirectoryList;


class Exportdata extends \Magento\Backend\App\Action
{
    protected $uploaderFactory;

    protected $_locationFactory; 

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Filesystem $filesystem,
        \[vendor_name]\[module_name]\Model\locatorFactory $locationFactory // This is returns Collaction of Data

    ) {
       parent::__construct($context);
       $this->_fileFactory = $fileFactory;
       $this->_locationFactory = $locationFactory;
       $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); // VAR Directory Path
       parent::__construct($context);
    }

    public function execute()
    {   
        $name = date('m-d-Y-H-i-s');
        $filepath = 'export/export-data-' .$name. '.csv'; // at Directory path Create a Folder Export and FIle
        $this->directory->create('export');

        $stream = $this->directory->openFile($filepath, 'w+');
        $stream->lock();

        //column name dispay in your CSV 

        $columns = ['Col-1-name','Col-2-name','Col-3-name','Col-4-name','Col-5-name','Col-6-name','Col-7-name','Col-8-name','Col-9-name',];

            foreach ($columns as $column) 
            {
                $header[] = $column; //storecolumn in Header array
            }

        $stream->writeCsv($header);

        $location = $this->_locationFactory->create();
        $location_collection = $location->getCollection(); // get Collection of Table data 

        foreach($location_collection as $item){

            $itemData = [];

            // column name must same as in your Database Table 

            $itemData[] = $item->getData('col-1-name');
            $itemData[] = $item->getData('col-2-name');
            $itemData[] = $item->getData('col-3-name');
            $itemData[] = $item->getData('col-4-name');
            $itemData[] = $item->getData('col-5-name');
            $itemData[] = $item->getData('col-6-name');
            $itemData[] = $item->getData('col-7-name');
            $itemData[] = $item->getData('col-8-name');
            $itemData[] = $item->getData('col-9-name');

            $stream->writeCsv($itemData);

        }

        $content = [];
        $content['type'] = 'filename'; // must keep filename
        $content['value'] = $filepath;
        $content['rm'] = '1'; //remove csv from var folder

        $csvfilename = 'locator-import-'.$name.'.csv';
        return $this->_fileFactory->create($csvfilename, $content, DirectoryList::VAR_DIR);

    }


}

“我的班级”的一部分是

[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);
}

我的HTML文件是

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

我的Angular 2 Component方法是方法

<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>

1 个答案:

答案 0 :(得分:0)

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 => {});
  }

完全有其他方法可以实现这一目标,但这是我当前的工作版本。