繁体   English   中英

无法将文件从 Angular 8 上传到 .net 核心 2.2?

[英]Cannot Upload file from Angular 8 to .net core 2.2?

Angular HTML:

<input #file type="file" name="file" id="file" (click)="handleFileInput($event.target.files)"  />
  <input type="button" value="Save" (click) ="UploadForm()" />  

Angular 代码:

 this.formdata = new FormData();
    this.formdata.append('file', this.selectedfile);
    this.httpClient
    .post("https://localhost:44318/api/Trading/FileUpload", this.formdata).subscribe(res=>{ console.log(res) });

.Net Core Web API 代码:

public async Task<SingleResponseModel<Dictionary<string, int>>> FileUploadAsync([FromForm] IFormFile file)
        {
            string createdby = "abcd";
            SingleResponseModel<Dictionary<string, int>> singleResponseModel = new SingleResponseModel<Dictionary<string, int>>();
            FileUploadDocumentModel fileUploadDocumentModel = null;
            string pathToSave = string.Empty;
            string fullPath = string.Empty;

            try
            {
                pathToSave = Path.Combine(Directory.GetCurrentDirectory(), "Documents");
                if (file != null)
                {
                    fullPath = Path.Combine(pathToSave, file.FileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }

                 }
            }
catch(Exception ex)
{
throw ex;
}
}

我在上传文件时收到 [FromForm] IFormFile object null。 请让我知道如何解决这个问题?

看起来您没有将文件发送到您的组件。 所以试着这样写:

<input #file type="file" name="file" id="file" (click)="handleFileInput(file.files)"  />

让我举例说明如何上传文件。

上传.component.html

<input type="file" #file placeholder="Choose file" (change)="uploadFile(file.files)" 
            accept="image/x-png,image/gif,image/jpeg" multiple>

上传.component.ts

public uploadFile = (files) => {
  if (files.length === 0) {
      return;
  }

  const fileToUpload = files[0] as File;
  const formData = new FormData();
  formData.append('file', fileToUpload, fileToUpload.name);

  this.uploadService.uploadFile(formData)
      .subscribe(event => {
          if (event.type === HttpEventType.UploadProgress) {
              this.progress = Math.round(100 * event.loaded / event.total);
          } else if (event.type === HttpEventType.Response) {
              this.message = 'Upload success.';
              this.onUploadFinished.emit({ dbPath: event.body.dbPath});
          }
      });
}

实际服务方式

uploadFile(file: FormData): Observable<any> {
    return this.http.post(`${environment.baseApi}Upload`, 
        file, {reportProgress: true, observe: 'events'})
        .pipe(map(v => v));
}

ASP.NET 核心 controller

[HttpPost]
public IActionResult Upload([FromForm] FileDto fileDto)
{
    if (!ModelState.IsValid)
    {
         return BadRequest(ModelState);
    }   

    if (fileDto.File != null)
    {                
        return Ok(new { dbPath = _uploadFileService.UploadFile(fileDto.File ) });
    }

    return BadRequest();
}

FileDto.cs

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;

namespace eshop.Persistence.Core.Dtos
{
    public class FileDto
    {
        public IFormFile File { get; set; }

        public string FolderPath { get; set; }

        public string FileName { get; set; }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM