文件上传和下载角4打字稿

Vic*_*ti. 15 typescript asp.net-core-webapi angular

我如何下载(.exe根路径中的文件)和从Angular 4(我是Angular4和typescript的新手)和Web API上传文件.我搜索了这个,但找不到解决方案.你能帮忙吗?这是我找到的链接.

示例链接

文件下载

谢谢Victor.A

MoM*_*oMo 23

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

这里有一些伪代码 - 请原谅phat手指.希望这可以帮助:

MyFileUploadComponent档案(.html):

...
<input type="file" (change)=fileEvent($event)...>
Run Code Online (Sandbox Code Playgroud)

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...');
     });
}
Run Code Online (Sandbox Code Playgroud)

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.
}
Run Code Online (Sandbox Code Playgroud)

  • return &lt;any&gt; post()吗?真的吗 (2认同)

Moh*_*ade 10

对于上传文件,我们可以以multipart/form-data的形式发布数据.为此,我们必须使用FormData类.这是一个例子.

模板:

<form #yourForm="ngForm" (ngSubmit)="onSubmit()">
      <input type="text" [(ngModel)]="Name" name="Name"/>
      <input type="file" #fileupload [(ngModel)]="myFile" name="myFile" (change)="fileChange(fileupload.files)"/>
      <button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

零件:

import { Http, Response, Headers, RequestOptions } from '@angular/http';
/* When we select file */
Name:string; 
myFile:File; /* property of File type */
fileChange(files: any){
    console.log(files);

    this.myFile = files[0].nativeElement;
}

/* Now send your form using FormData */
onSubmit(): void {
    let _formData = new FormData();
    _formData.append("Name", this.Name);
    _formData.append("MyFile", this.myFile);
    let body = this._formData;
    let headers = new Headers();
    let options = new Options({
        headers: headers
    });
    this._http.post("http://example/api/YourAction", body, options)
      .map((response:Response) => <string>response.json())
      .subscribe((data) => this.message = data);
}
Run Code Online (Sandbox Code Playgroud)

要上传API文件,请访问:https:
//docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2

  • 魔法!你使用`Headers()`和`Options()`.他们从哪里进口?角?别的地方?如果Angular,Angular在哪里?谨慎提供全面的答案.Geesh. (2认同)