Угловая загрузка node.js response.sendFile - PullRequest
0 голосов
/ 21 мая 2019

На данный момент моя служба nodejs делает это:

...
fs.writeFileSync('filelocation/data.xlsx', theData, 'binary');
reponse.sendFile('filelocation/data.xlsx');
reponse.download('filelocation/data.xlsx'); // I tried this one also
...

Но как мне теперь загрузить это из Angular front end, используя HttpClient?Это не работает:

this.httpclient.get(url).subscribe(response => {
  console.log(response); // Or whatever I need to do to download the file
});

Я хочу, чтобы вызов вызвал проводник, чтобы я мог сохранить файл.Как мне заставить это работать?Если вам нужна дополнительная информация от меня, просто дайте мне знать, пожалуйста.

1 Ответ

1 голос
/ 21 мая 2019

создайте component.ts и передайте имя файла в fileService. Внутри fileService создайте функцию загрузки и с помощью этого передайте имя файла бэкэнд-серверу. Файл может быть загружен с помощью «saveAs». Установите файловую заставку ( npm установить файловую заставку --save ) и импортируйте 'saveAs' в компонент веб-интерфейса.

Download(filename){
    console.log(filename);
    this.fileService.download(filename).subscribe((data)=>{
        console.log(data);
        saveAs(data, filename);
    });
}

Component.ts

download(filename){
    const fileObj = {
        filename : filename
    };
    console.log(fileObj);
    return this.http.post(`http:localhost:3000/download`, fileObj, {
        responseType : 'blob',
    });
} 

fileService.ts

app.post('/download', (req, res, next) => {
    console.log('here');
    filepath = path.join(__dirname,'../uploadedFiles') + '/' + req.body.filename;
    console.log(filepath);
    res.sendFile(filepath);
});

Server.js

...