Skip to main content
 首页 » 编程设计

c#之使用 Angular 6 将文件上传到 Web Api C#

2024年02月04日28Terrylee

我有 Angular CLI 应用程序和 Dot net core 2.0 Web API。我需要将文件从 Angular 上传到 Web API。从 Web API 到服务器。当我使用 Http 时,它工作正常。使用 HttpClient 时,它不起作用。 这是我的 component.ts 代码:

fileChange(event, grdvalue) { 
debugger; 
let fileList: FileList = event.target.files; 
if (fileList.length > 0) { 
  let file: File = fileList[0]; 
  const formData: FormData = new FormData(); 
  let GridName = grdvalue; 
 
  formData.append('file', file, file.name); 
  formData.append('Id', this.userId); 
  formData.append('GridValue', GridName) 
 
  this.myService.PostFileToAzure(formData).subscribe(details => { 
    debugger; 
  }, 
    (error) => { 
      debugger; 
    }) 
  } 
 } 

这是我的服务代码:

 PostFileToAzure(form) { 
    debugger; 
    var body = JSON.stringify(form); 
    return this.http.post(this.baseApiURL + '/Interpretation/InterpreterFileUpload', form); 
} 

这是我的 Web API 代码:

[HttpPost("InterpreterFileUpload")] 
    public async Task<IActionResult> InterpreterFileUpload() 
    { 
        try 
        { 
 
            var file = Request.Form.Files[0]; 
            HttpRequest formData = HttpContext.Request; 
        } 
    } 

如何使用 HttpClient 从 Angular 向 Web API 发送文件。我在 Web API 中遇到错误,例如“不正确的内容类型:application/json”

请您参考如下方法:

在 Angular 站点使用此代码

file: any; 
 
onSelectFile($event, file) { 
    this.file = file; 
  } 
 
 
  uploadImage() { 
    if (this.file.length === 0) { 
      return; 
    } 
 
    const formData = new FormData(); 
 
    for (let file of this.file) 
      formData.append(file.name, file); 
 
    const uploadReq = new HttpRequest('POST', `api/FileUpload`, formData, { 
      reportProgress: true, 
    }); 
 
    this.http.request(uploadReq).subscribe(event => { 
      if (event.type === HttpEventType.UploadProgress) { 
        this.progress = Math.round(100 * event.loaded / event.total); 
      } 
    }); 
  } 

这里 onSelectFile 应该像这样在输入时被调用

<input #file type='file' multiple (change)="onSelectFile($event, file.files)"> 

然后在您的 asp.net 站点上使用此代码

[Produces("application/json")] 
    [Route("api/[controller]")] 
    public class FileUploadController : Controller 
    { 
    private IHostingEnvironment _hostingEnvironment; 
 
    public FileUploadController(IHostingEnvironment hostingEnvironment) 
    { 
      _hostingEnvironment = hostingEnvironment; 
    } 
 
    [HttpPost, DisableRequestSizeLimit] 
    public ObjectResult UploadFile() 
    { 
      try 
      { 
        var file = Request.Form.Files[0]; 
        string folderName = "Upload"; 
        string webRootPath = _hostingEnvironment.WebRootPath; 
        string newPath = Path.Combine(webRootPath, folderName); 
        if (!Directory.Exists(newPath)) 
        { 
          Directory.CreateDirectory(newPath); 
        } 
        string fileName = ""; 
        if (file.Length > 0) 
        { 
          fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); 
          string fullPath = Path.Combine(newPath, fileName); 
          using (var stream = new FileStream(fullPath, FileMode.Create)) 
          { 
            file.CopyTo(stream); 
          } 
        } 
 
        return Ok(fileName); 
      } 
      catch (System.Exception ex) 
      { 
        return BadRequest(ex.Message); 
      } 
    } 
  } 

谢谢