Download file with Casperjs

829 views Asked by At

I am trying to download a csv file using casperjs but I cannot find the correct way!

I have the following simple php page which include an image inside a form. When the user clicks the image, the csv file is downloading. Here is the code:

<?php

if (isset($_POST['foo_x'])) {
    header('Content-disposition: attachment; filename=file1.csv');
    header('Content-type: text/x-comma-separated-values; charset=iso-8859-7');
}

$foo_x=$_POST['foo_x'];
$foo_y=$_POST['foo_y'];
echo "X=$foo_x, Y=$foo_y ";

?>

<html>
<head>
<body>

<form action='' method=post>
    <input type="text"><br>
    <input type="image" alt='image description' src="image1.jpg" name="foo" id="foo"/>
</form>

</body>
</head>
</html>

In order to simulate the downloading process with casperjs, I have written the following code, that unfortunately doesn't work!!

var casper = require('casper').create({
    loadImages:false,
    verbose: true,
    logLevel: 'debug'
});

casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X)');

casper.start('http://localhost/input_image_test/', function() {

    this.click('#foo');

    casper.on('resource.received', function(resource) {
        if (resource.stage !== "end") {
            console.log("resource.stage !== 'end'");
            return;
        }
        if (resource.url.indexOf('file1.csv') > -1) {
            console.log("Downloading csv file");
            var fs = require('fs');
            this.download(resource.url, fs.workingDirectory+'/file1.csv');
        }
    });

});

casper.run();

Can anyone help how to fix the code? What is wrong and the casperjs code cannot download the file1.csv? Thanks a lot!

0

There are 0 answers