Node.js Download File Using Content Disposition as Filename

前端 未结 3 993
栀梦
栀梦 2021-02-01 17:22

I\'m using the Request module to download files, but I\'m not quite sure how to pipe the response to an output stream when the filename must come from the \'Content-Disposition\

3条回答
  •  庸人自扰
    2021-02-01 18:06

    Question has been around a while, but I today faced the same problem and solved it differently:

    var Request = require( 'request' ),
        Fs = require( 'fs' );
    
    // RegExp to extract the filename from Content-Disposition
    var regexp = /filename=\"(.*)\"/gi;
    
    // initiate the download
    var req = Request.get( 'url.to/somewhere' )
                     .on( 'response', function( res ){
    
                        // extract filename
                        var filename = regexp.exec( res.headers['content-disposition'] )[1];
    
                        // create file write stream
                        var fws = Fs.createWriteStream( '/some/path/' + filename );
    
                        // setup piping
                        res.pipe( fws );
    
                        res.on( 'end', function(){
                          // go on with processing
                        });
                     });
    

提交回复
热议问题