8

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

Fabio Cicerchia
  • 649
  • 3
  • 8
  • 23
  • @Ros - you seemed to have the start of a possible answer there, please see if you can rephrase it to state your conclusion more clearly. – Chris Stratton May 07 '14 at 17:01

2 Answers2

4

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!)

Darren Cook
  • 27,837
  • 13
  • 117
  • 217
  • 1
    Please have the good manners to comment when downvoting. (I've just re-read this answer and I still think it is not just a good answer, but the correct one - I've had the same problem as the OP, and have used all three of my suggestions at various times. So I'm very curious to hear more about why you think it is wrong.) – Darren Cook Apr 11 '14 at 00:22
1

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.

Fabio Cicerchia
  • 649
  • 3
  • 8
  • 23