Uploading file in Yii using ajax

最后都变了- 提交于 2020-01-14 12:47:11

问题


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>

<

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;
}
?>

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


回答1:


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

Also watch 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();


来源:https://stackoverflow.com/questions/21061989/uploading-file-in-yii-using-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!