Programming/JavaScript & TypeScript

Node.js-Angular 파일 다운로드 기능 구현

Bonita SY 2020. 1. 26. 14:49
728x90
반응형

1. file-saver 모듈 다운로드

npm i --save file-saver

https://www.npmjs.com/package/file-saver

 

file-saver

An HTML5 saveAs() FileSaver implementation

www.npmjs.com

2. Angular (Client) 부분

let headers = new HttpHeaders({
    "Authorization": "Bearer " + user.jwt, // Auth header
    //No other headers needed
});

this.http
    .get("/download/dump", { headers, responseType: "blob" }) //set response Type properly (it is not part of headers)
    .toPromise()
    .then(blob => {
        saveAs(blob, "dump.gz"); 
    })
    .catch(err => console.error("download error = ", err));

 

3. Node.js (Server) 부분

app.get( "/download/dump", authenticate, (req:Request, res:Response) => {
    const file = path.resolve(__dirname, `./dumps/dump.gz`);
    //No need for special headers
    res.download(file); 
})

 

출처

https://stackoverflow.com/questions/56219373/node-angular-download-a-file-with-http-request

 

Node + Angular : download a file with HTTP request

I tried 400 combinations of syntaxes and headers, I can't figure out how to make a HTTP call from Angular to retrieve a file from my NodeJS server. Found on Stackoverflow and tried, to no avail :

stackoverflow.com

http://expressjs.com/ko/api.html#res.download

 

Express 4.x - API 참조

Express 4.x API express() Creates an Express application. The express() function is a top-level function exported by the express module. var express = require('express') var app = express() Methods express.json([options]) This middleware is available in Ex

expressjs.com

 

728x90
반응형