개발 창고/NodeJS
[Express] 파일 다운로드
로이제로
2022. 10. 13. 13:48
반응형
res.download(path [, filename] [, options] [, fn])
path : 다운로드할 파일의 경로
filename : 다운로드 받을 파일 이름
options : 다운로드 설정
fn : callback 처리
사용방법
const express = require('express');
const app = express();
/**
* 첨부파일 다운로드
*/
app.get('/api/file/download', async(req, res) => {
const filepath = "/filepath/filename.txt"
const filename = "downfile.txt";
if(fs.existsSync(filepath)){
res.download(filepath, filename);
}else{
res.status(403).send({ errMsg: "해당 파일이 존재하지 않습니다.[1]" });
}
});
const port = process.env.PORT || 3001;
app.listen(port, function () {
console.log('listening on ' + port)
});
/filepath라는 폴더 경로에 있는 filename.txt라는 파일을 downfile.txt라는 이름으로 다운로드하는 예시입니다.
반응형