How to make a POST file using CasperJS via simple Javascript, not through the interface

I cannot figure out how to do the following:

Before running my tests, I would like to send a (multipart) file to the server. Our backend creates content profiles for these downloads, which can then be accessed through the interface. This content profile I need to run tests.

I know the functionality of .fill (), but this does not apply, since I do not want to upload files through the user interface. Is there a way this can be achieved with CasperJS or javascript, or can someone point me to the documentation that can help me?

+4
source share
3 answers

Check this.page.upload file, as the phantom browser does not have ui to select the file, you can use it to specify the file name, and then click submit.

phantom.casperPath = '{PATH_TO_CASPER_JS}'; phantom.injectJs(phantom.casperPath + '\\bin\\bootstrap.js'); var system = require('system') var page = require('webpage').create(); var casper = require('casper').create(); function getReturnedText() { return document.querySelector('#ocr-result').innerText; } casper.start('http://www.newocr.com/', function() { this.page.uploadFile('input[type="file"]', '{PATH_TO_JPEG}'); this.click('button[name="preview"]'); }); casper.thenEvaluate(function() { this.click('button[name="ocr"]'); }); casper.run(function() { this.echo(getReturnedText()); phantom.exit(1); }); 
+1
source

As far as I read the documentation of both casperjs and phantomjs, direct file representations are not allowed. You can use curl as shown below:

 curl http://some.testserver.com/post.php \ -F file_input=@ /path/to/my/file.txt \ -F "text_field=Some Text Here" \ -F some_number=1234 

However, you can open a POST request on casperjs:

 casper.start(); casper.open('http://some.testserver.com/post.php', { method: 'post', data: { 'title': 'Plop', 'body': 'Wow.' }, headers: { 'Content-type': 'multipart/form-data' } }); casper.then(function() { this.echo('POSTED it.'); }); casper.run(); 

Here is the relevant documentation:

http://docs.casperjs.org/en/latest/modules/casper.html#open

+7
source

Try the following:

 casper.thenOpen('about:blank', function(){ this.evaluate(function(){ var action = 'upload.php' var html = '<form action="'+action+'" method="post" enctype="multipart/form-data">' html += '<input type="file" name="files[]" multiple="multiple">' html += '<button type="submit">Submit</button>' html += '</form>' document.write(html) }) this.fill('form',{ 'files[]': 'file.txt' }, true) this.waitFor(function(){ var uri = casper.evaluate(function(){ return document.documentURI }) if ( 'about:blank' === uri ){ return false } return true }) }) 
+1
source

Source: https://habr.com/ru/post/1490756/


All Articles