网路上有很多讲 Angular 如何实作上传功能的文章,但讲怎么做下载功能的却很少。
There are many articles talk about how to upload file with Angular + NodeJS, but few about downloading file.
这边简单示範如何用 Angular 5 搭配 NodeJS 做到档案下载的功能。
Here I show how to use Angular 5 with NodeJs to implement downloading file function.
app.service.ts
:
downloadFile() { return this.http.post( this.API_LINK.DOWNLOAD, { data: data // POST 的 Body }, { headers: this.header, responseType: 'blob' // 注意这边要选 `blob` });}
app.component.ts
:
import { saveAs } from 'file-saver'; // 引入前记得要装: npm install file-saver// ...// ...download() { this.service.downloadFile() .subscribe(res => { const blob = new Blob([res], { type: 'application/zip' }); // 档案类型 file type const filename = 'files.zip'; // 你想存的名字 The name you want to save saveAs(blob, filename); });}
Node.js 搭配 express
:
api.post('/download', (req, res) => { // ... // FILEPATH 填入要被下载档案的路径 // FILENAME 无所谓,因为会被 Angular 定义的新名称盖掉 res.download(FILEPATH, FILENAME, err => { if (err) { logger.error(err); } else { // } })})
关于作者
刘安齐
软体工程师,热爱写程式,更喜欢推广程式让更多人学会
个人网站GithubFB粉专--微中子