Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhantomJS - Upload a file without submitting a form

Is it possible to upload a file to a certain page using PhantomJS without submitting manually the form? I think something is possible using the Content-Type: multipart/form-data.

The example on https://github.com/ariya/phantomjs/blob/master/examples/imagebin.js is working fine, but I want to send directly the file in the POST request without interacting with any element.

Any suggestion?

Thank you very much

like image 853
Fabio Cicerchia Avatar asked Dec 07 '13 23:12

Fabio Cicerchia


2 Answers

File uploads can be done over AJAX (as of xhr2 - if you need to support older browsers, use something like jQuery-File-Upload; there is a good tutorial here on using it just to do the upload part, and not using Blueimp's UI.) That is related to the "without manually submitting the form" part of your question. You will still need to interact with a file upload element to choose the file, and that is where you use page.uploadFile().

To do it solely from JavaScript, without "interacting with any element on the page", you could use page.evaluate() to run some custom JavaScript. It could then use the File Reader API to find the file on local disk, store it in a blob, then upload that blob over AJAX. The WebKit in PhantomJS (roughly equivalent to Chrome 13) should work, as apparently the FileReader API has been there since Chrome 6.

(BTW, if all you wanted to do is upload a file to a server using a headless script, PhantomJS is overkill, and you could use curl. But I'm assuming you want to use PhantomJS for some other reason!)

like image 88
Darren Cook Avatar answered Nov 15 '22 03:11

Darren Cook


The solution I've used at the end is a mix of NodeJS and PhantomJS, in case I need to upload something I fork a process and upload the file(s) using the NodeJS "request" module and then send back to PhantomJS the output of the page, which need to be manually processed.

like image 23
Fabio Cicerchia Avatar answered Nov 15 '22 05:11

Fabio Cicerchia