使用ajax在Yii上传文件

时间:2014-01-11 12:02:55

标签: php jquery ajax yii yii-components

我正在尝试使用像facebook聊天这样的jj从popover实现文件上传。我发现使用ajax提交按钮,它无法上传Yii中的文件。所以我尝试使用像php方法。这是我找到的php方法,它运行良好。

<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image: 
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />

</div>
</form>

&LT;

script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function() 
{ 

$('#photoimg').live('change', function() 
 {
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");

$("#imageform").ajaxForm({target: '#preview', 
beforeSubmit:function(){
A.show();
B.hide();
}, 
success:function(){
A.hide();
B.show();
}, 
error:function(){
A.hide();
B.show();
} }).submit();
});

}); 
</script>



    <?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";

function getExtension($str)
{
$i = strrpos($str,".");
if (!$i)
{
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB"; 
}
else
echo "Invalid file format.."; 
}
else
echo "Please select image..!";
exit;
}
?>

我想知道Yii中是否有任何方法可以从表单调用控制器操作?

1 个答案:

答案 0 :(得分:3)

实际上Yii有文件上传类。要进行验证,您可以使用模型规则:

array('url_img', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'wrongType'=>Yii::t('app','bad_file')),

您可以使用ajax上传文件,例如:

var fd = new FormData();
fd.append( "ModelName[image]", $("#your_input_id")[0].files[0]);
$.ajax({
        url: url,
        type: 'POST',
        cache: false,
        data: fd,
        dataType: "json",
        processData: false,
        contentType: false,
        success: function (data) {
        }
}); 

要保存文件,请执行以下操作:

$model=new ModelName;
CUploadedFile::getInstance($model,"image");
if ($model->validate()){
    $model->image->saveAs("path/to/save/image.png");
}

另请注意http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/

在你看来,你会有这样的事情:

$form = $this->beginWidget(
    'CActiveForm',
    array(
        'id' => 'upload-form',
        'enableAjaxValidation' => false,
        'htmlOptions' => array('enctype' => 'multipart/form-data'),
    )
);
// ...
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
// ...
echo CHtml::submitButton('Submit');
$this->endWidget();