簡體   English   中英

將文件從NodeJS Server下載到本地計算機

[英]Download file from NodeJS Server to local machine

我想將一個TextFile從NodeJS服務器下載到以AngularJS為前端的客戶端本地計算機。 客戶端存儲路徑位於本地計算機上的downloads / testdownload中。

在我的后端,我有:

router.get('/upload', function(req, res){
    var data= fs.readFileSync('../uploads/'+ file);
      fs.writeFile(??+req.file.filename, file, function(err){
          if(err){
              return console.log(err);
          }
          console.log('Saved File: ' + req.file.filename);
      })
})

在我的角度:

this.download= function(){
        $http.get('/creations/upload').then(function success(response){
                    console.log(response.data);

            }, function error(response){
              response.data;
         })
    }

我用一個按鈕鏈接了這個功能。 我必須在nodejs fs.writeFile函數中寫入什么路徑才能將文件保存到本地計算機/ downloads / testfile?

這將幫助您..在這里,我使用busboy進行發布和獲取文件。

這是后端代碼。 只是您必須從前端調用此api。

'use strict'

var express = require('express');
var router = express.Router();
var fs = require('fs-extra');


//Get file
router.get('/:file', function(req, res, next) {
  //this is where your file will be downloaded    
  var filenamewithpath = '/home/downloads/' + req.params.file;

  if (!fs.existsSync(filename)){
    res.status(404).json({'message' : 'file not found'})
    return;
  }
  res.download(filename , fileToShow)
});

//Post file
router.post('/', function(req, res, next) {    
  req.pipe(req.busboy);
  req.busboy.on('file', function (fieldname, file, filename) {    
    var fstream = fs.createWriteStream('/home/temp/' + filename);   
    file.pipe(fstream);    
    fstream.on('close', function () {
      res.status(201).json({file: filename});
    });
  });
});

module.exports = router;

如果您知道服務器中文件的完整路徑,則可以將其放在html錨標記中以進行下載,對嗎?

<a href="http://<path to file>">Download</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM