我正在尝试使用CasperJS将图像上传到网络表单。
我的表单看起来像这样:
<form action="" method="POST" enctype="multipart/form-data" class="form-vertical">
...
<legend>Campaign Banner</legend>
<div class="control-group image-field ">
<label class="control-label">Now Large</label>
<div class="controls">
<div class="file-field"><input id="id_now_large_image" name="now_large_image" type="file"></div>
<div class="image-preview"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group image-field ">
<label class="control-label">Now Medium</label>
<div class="controls">
<div class="file-field"><input id="id_now_medium_image" name="now_medium_image" type="file"></div>
<div class="image-preview"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group image-field ">
<label class="control-label">Now Small</label>
<div class="controls">
<div class="file-field"><input id="id_thumbnail_image" name="thumbnail_image" type="file"></div>
<div class="image-preview now-small"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
提交按钮如下所示:
<div class="form-actions">
<button type="submit" class="btn btn-small ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text">Save changes</span></button>
</div>
我在这里写了完整HTML的要点:https://gist.github.com/victorhooi/8277035
首先,我尝试使用CasperJS的fill方法:
this.fill('form.form-vertical', {
'now_large_image': '/Users/victor/Dropbox/CMT Test Resources/Test Banners/Default Banners/now_large.jpg',
}, false);
this.click(x('//*[@id="content-wrapper"]//button/span'));
我也做了一个this.capture(),我看到文件字段已填入:
我没有使用fill方法的内置提交,但我自己点击了提交按钮:
this.click(X( '// * [@ ID = “内容封装器”] //按钮/跨度'));
然后我再做一次捕获,我可以看到表单已经提交:
但是,图像似乎根本没有上传。
我也尝试过使用PhantomJS的uploadFile()方法:
this.page.uploadFile('input[name=now_large_image]', '/Users/victor/Dropbox/CMT Test Resources/Test Banners/Default Banners/now_large.jpg');
然后点击提交按钮。
同样的问题 - 填写表单字段 - 但是,图像本身似乎没有被提交。
有关如何在此处正确上传图片的任何想法?
答案 0 :(得分:4)
由于您正在填写并成功提交,请在点击时尝试Wait命令。
casper.then(function() {
//+++ form fill here
//waits 1 sec
this.wait(1000, function() {
this.click(x('//*[@id="content-wrapper"]//button/span'));
});
});
答案 1 :(得分:0)
试试这个。
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
})
})