cakephp之Ajax异步文件上传<摘录>

why?

同一个需要填写信息和上传文件,一步步保存避免信息丢失。
how?

尝试按照cookbook 使用'prototype.js'

echo $javascript->link('prototype');
echo $javascript->link('scriptaculous');

表单中使用ajaxHelper设置提交按钮

<form name="uploadForm" id="uploadForm" enctype="multipart/form-data" action="/AppFiles/uploadFile" method="POST">

<input name="uploadedfile" type="file" /><br />

<input name="fname" type="text" /><br />

echo $ajax->submit('Upload File', array('url'=> array('controller'=>'AppFiles', 'action'=>'uploadFile'), 'update' => 'testdiv'));

在controller中发现不能使用$_FILE['uploadedfile']['name']或其他方法如$this->params['form'][‘uploadedfile’]获取信息,而正常的文本fname的值则可通过$this->params['form']['fname']获取。
solution?

搜索发现一本 begging cakePHP的书讲ajax upload

“The reason why I’ve used jQuery here is that it is the only Ajax framework I’ve been able to find that will serialize the form elements and actually send to the server as a post variable the1 <input type="file">element.”

好吧!改用jquery库试试

echo $javascript->link('jquery-1.4.2.min.js');
echo $javascript->link('jquery.form.js');   //不可缺少

<form name="uploadForm" id="uploadForm" enctype="multipart/form-data" action="/AppFiles/uploadFile" method="POST">
<div id="testdiv"
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />

<?php echo $this->Form->button('Upload Text',array('onClick'=>'$(\'#uploadForm\').ajaxSubmit(

{target: \'#testdiv\',url: \''.$html->url('/AppFiles/uploadFile').'\'}

); return false;'));?>

</div>
</form>
controller中使用basename( $_FILES['uploadedfile']['name']) 获取不包含目录的文件名

ok 成功!

参考文献:http://www.davidgolding.net/cakephp/ajax-file-uploading-with-cake-and-jquery.html

你可能感兴趣的:(JavaScript,jquery,Ajax,prototype,cakephp)