Serving Temporary Files with NodeJs

后端 未结 2 2102
礼貌的吻别
礼貌的吻别 2021-02-04 09:52

I am building a NodeJs SOAP client. Originally, I imagined the server (ie the node SOAP client) would allow downloading documents through a REST API (the REST API is authentica

相关标签:
2条回答
  • 2021-02-04 10:07

    If you are visiting this SO page after Dec 2015, you may find that the previous solution isn't working (At least it isn't working for me). I found a different solution so I thought I would provide it here for future readers.

    app.get('/download', function(req, res){
        res.download(pathToFile, 'fileNameForEndUser.pdf', function(err) {
            if (!err) {
                fs.unlink(path);
            }
        });
    });
    
    0 讨论(0)
  • 2021-02-04 10:16

    Found two SO questions that answer my question. So apparently we don't need to use the express.static middleware. We just need the filesystem to download a file:

    app.get('/download', function(req, res){
     var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
     res.download(file); // Set disposition and send it.
    });
    

    If we want to stream and then delete follow:

    app.get('/download', function(req, res){
       var stream = fs.createReadStream('<filepath>/example.pdf', {bufferSize: 64 * 1024})
       stream.pipe(res);
    
       var had_error = false;
       stream.on('error', function(err){
          had_error = true;
       });
       stream.on('close', function(){
       if (!had_error) fs.unlink('<filepath>/example.pdf');
    });
    
    0 讨论(0)
提交回复
热议问题