@@ -25,6 +25,8 @@ const ElementNotFound = require('./errors/ElementNotFound');
2525const RemoteBrowserConnectionRefused = require ( './errors/RemoteBrowserConnectionRefused' ) ;
2626const Popup = require ( './extras/Popup' ) ;
2727const Console = require ( './extras/Console' ) ;
28+ const axios = require ( 'axios' ) ;
29+ const fs = require ( 'fs' ) ;
2830
2931
3032let puppeteer ;
@@ -851,6 +853,55 @@ class Puppeteer extends Helper {
851853 return proceedClick . call ( this , locator , context , { waitForNavigation : true } ) ;
852854 }
853855
856+ /**
857+ * {{> ../webapi/downloadFile }}
858+ */
859+ async downloadFile ( locator , customName ) {
860+ let fileName ;
861+ await this . page . setRequestInterception ( true ) ;
862+ this . click ( locator ) ;
863+
864+ const xRequest = await new Promise ( ( resolve ) => {
865+ this . page . on ( 'request' , ( request ) => {
866+ const grabbedFileName = request . url ( ) . split ( '/' ) [ request . url ( ) . split ( '/' ) . length - 1 ] ;
867+ const fileExtension = request . url ( ) . split ( '/' ) [ request . url ( ) . split ( '/' ) . length - 1 ] . split ( '.' ) [ 1 ] ;
868+ customName ? fileName = `${ customName } .${ fileExtension } ` : fileName = grabbedFileName ;
869+ request . abort ( ) ;
870+ resolve ( request ) ;
871+ } ) ;
872+ } ) ;
873+
874+ const options = {
875+ encoding : null ,
876+ method : xRequest . _method ,
877+ uri : xRequest . _url ,
878+ body : xRequest . _postData ,
879+ headers : xRequest . _headers ,
880+ } ;
881+
882+ const cookies = await this . page . cookies ( ) ;
883+ options . headers . Cookie = cookies . map ( ck => `${ ck . name } =${ ck . value } ` ) . join ( ';' ) ;
884+
885+ const response = await axios ( {
886+ method : options . method , url : options . uri , headers : options . headers , responseType : 'arraybuffer' ,
887+ } ) ;
888+
889+ const outputFile = path . join ( `${ global . output_dir } /${ fileName } ` ) ;
890+
891+ try {
892+ return new Promise ( ( resolve , reject ) => {
893+ const wstream = fs . createWriteStream ( outputFile ) ;
894+ wstream . write ( response . data ) ;
895+ wstream . end ( ) ;
896+ this . debug ( `File is downloaded in ${ outputFile } ` ) ;
897+ wstream . on ( 'finish' , ( ) => { resolve ( fileName ) ; } ) ;
898+ wstream . on ( 'error' , reject ) ;
899+ } ) ;
900+ } catch ( error ) {
901+ throw new Error ( `There is something wrong with downloaded file. ${ error } ` ) ;
902+ }
903+ }
904+
854905 /**
855906 * {{> ../webapi/doubleClick }}
856907 */
0 commit comments