文件上传和下载角度 4 打字稿 [英] File upload and download in angular 4 typescript

查看:32
本文介绍了文件上传和下载角度 4 打字稿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Angular 4 下载(位于根路径中的 .exe 文件)并上传文件?
我是 Angular4 和 typescript 以及 .NET Core Web API 的新手.

How can I download (.exe file which is in root path) and Upload a file from Angular 4?
I am new to Angular4 and typescript and .NET Core Web API.

我已经用谷歌搜索了这个,但找不到解决方案.

I have googled for this but could not find the solution.

以下是我发现的一些类似问题:

Here are some similar questions that I found:

返回二进制文件来自 ASP.NET Web API 中的控制器的文件

推荐答案

我想为此添加一个 Angular 4.3/5/6/7/8 更新,特别是针对简化的 HttpClient.'Content-Type' 的缺失尤为重要,因为 Angular 会自动构造 Content-Type(有添加 Content-Type=undefined 的倾向.不要,因为它会在各种情况下产生问题,也许不会好的做法).一旦没有Content-Type,浏览器会自动添加'multipart/form-data'和相关参数.请注意,这里的后端是 Spring Boot,尽管它应该无关紧要.

I'd like to add an Angular 4.3/5/6/7/8 update for this especially vis-a-vis the simplified HttpClient. The absence of the 'Content-Type' is especially important since Angular automatically constructs the Content-Type (there is a propensity to add Content-Type=undefined. Don't, as it will create issues under various circumstances and, perhaps, not good practice either). Once there is no Content-Type, the browser will automatically add 'multipart/form-data' and associated parameters. Note, the backend here is Spring Boot although it shouldn't matter.

这是一些伪代码——请原谅我的手指.希望这会有所帮助:

Here's some pseudo code--please excuse phat fingers. Hope this helps:

MyFileUploadComponent(.html):

...
<input type="file" (change)=fileEvent($event)...>

MyFileUploadComponent(.ts) 在 fileEvent 上调用 MyFileUploadService(.ts):

...
public fileEvent($event) {
   const fileSelected: File = $event.target.files[0];
   this.myFileUploadService.uploadFile(fileSelected)
   .subscribe( (response) => {
      console.log('set any success actions...');
      return response;
    },
     (error) => {
       console.log('set any error actions...');
     });
}

MyFileUploadService.ts:

...
public uploadFile(fileToUpload: File) {
  const _formData = new FormData();
  _formData.append('file', fileToUpload, fileToUpload.name);   
  return<any>post(UrlFileUpload, _formData); 
  //note: no HttpHeaders passed as 3rd param to POST!
  //So no Content-Type constructed manually.
  //Angular 4.x-6.x does it automatically.
}
  

这篇关于文件上传和下载角度 4 打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆