How to return ftp files to browsers by Node.js

use the ftp package in Node.js to upload and download files. Referring to the demo, given on github, you can now download files from ftp servers locally. The code is as follows:

var tool = require("../utils/tool");
router.get("/download", function (req, res) {
    var url = req.query.url 

    var Client = require("ftp");
    var fs = require("fs");

    var c = new Client();
    c.on("ready", function() {
        c.get(url, function(err, stream) {
            if (err) throw err;
            stream.once("close", function() { c.end(); });
            stream.pipe(fs.createWriteStream("/Users/dbman/Desktop/test.txt"));
        });
    });

    var option={host:"","port":"","user":"","password":""}  
    c.connect(option);

    var result = tool.responseSuccess("ok");
    return res.json(result);

});

now I want to implement such a function: when the user clicks a button in the browser, the interface written above will be called, and the browser will pop up the download window and allow the user to customize the save path. How should the above interface be modified?

Mar.18,2021

  • .pipe (res); forward the ftp response directly
  • Content-Disposition: attachment; filename= "xxx" set the HTTP header to let the browser click "Save as"
Menu