PhantomJS - 上传文件而不提交表单 [英] PhantomJS - Upload a file without submitting a form

查看:24
本文介绍了PhantomJS - 上传文件而不提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 PhantomJS 将文件上传到某个页面而无需手动提交表单?我认为使用 Content-Type: multipart/form-data 是可能的.

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.

https://github.com/ariya/phantomjs/blob/master/上的示例examples/imagebin.js 工作正常,但我想直接在 POST 请求中发送文件而不与任何元素交互.

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.

有什么建议吗?

非常感谢

推荐答案

文件上传可以通过 AJAX 完成(从 xhr2 开始 - 如果您需要支持旧版浏览器,请使用类似 jQuery-File-Upload; 有 这里有一个很好的教程,它只用于上传部分,而不是使用 Blueimp 的 UI.)这与无需手动提交表单"有关你问题的一部分.您仍然需要与文件上传元素进行交互以选择文件,这就是您使用 page.uploadFile() 的地方.

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().

要仅通过 JavaScript 完成,而不与页面上的任何元素交互",您可以使用 page.evaluate() 来运行一些自定义 JavaScript.然后它可以使用 File Reader API 在本地磁盘,将其存储在 blob 中,然后通过 AJAX 上传该 blob.PhantomJS 中的 WebKit(大致相当于 Chrome 13)应该可以工作,因为显然 FileReader API 自 Chrome 6 以来就已经存在.

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.

(顺便说一句,如果您只想使用无头脚本将文件上传到服务器,那么 PhantomJS 就太过分了,您可以使用 curl.但我假设您想使用PhantomJS 出于其他原因!)

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

这篇关于PhantomJS - 上传文件而不提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆