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

查看:87
本文介绍了用angular 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 3d param to POST!
  //So no Content-Type constructed manually.
  //Angular 4.x-6.x does it automatically.
}

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

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