iT邦幫忙

2

Angular Download Implementation with NodeJS 檔案下載實作

網路上有很多講 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 {
      // 
    }
  })
})

關於作者

劉安齊

軟體工程師,熱愛寫程式,更喜歡推廣程式讓更多人學會


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言