使用AJAX的Yii上传文件 [英] Uploading file in Yii using ajax

查看:168
本文介绍了使用AJAX的Yii上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现文件上传使用AJAX像Facebook聊天一个popover。我发现,使用AJAX提交按钮,它不能上传文件在Yii中。所以我试图用PHP之类的方法。下面是PHP的方法,我发现,这是很好的工作。

I am trying to implement file upload from a popover using ajax like facebook chat . I found that using ajax submit button, it is not able to upload files in Yii. So I tried to use like php method. Here is the php method I found, which is well working.

<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中的任何方法调用的形式控制器操作?

I would like to know is there any method in Yii to call controller action from form ?

推荐答案

其实Yii的具有文件上传类。为了验证你可以用模型的规则:

Actually Yii have file upload class. For validation you can use model rules:

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

您可以上传文件,阿贾克斯,例如:

You can upload files with ajax, for example:

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) {
        }
}); 

要保存文件,简单的做:

To save file, simple do:

$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/

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

In your view you'll have something like this:

$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();

这篇关于使用AJAX的Yii上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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