我正在使用xupload扩展,它基于blueimp jquery fileuploader,虽然我可以成功上传到该文件夹,但我无法将路径和其他详细信息添加到数据库中。以下是按顺序的上传操作和模型。请帮忙。感谢。
public function actionUpload( ) {
//Here we define the paths where the files will be stored temporarily
$path = Yii::app() -> getBasePath() . "/../images/";
$publicPath = Yii::app()->getBaseUrl( )."/images/";
//This is for IE which doens't handle 'Content-type: application/json' correctly
header( 'Vary: Accept' );
if( isset( $_SERVER['HTTP_ACCEPT'] )
&& (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) {
header( 'Content-type: application/json' );
} else {
header( 'Content-type: text/plain' );
}
//Here we check if we are deleting and uploaded file
if( isset( $_GET["_method"] ) ) {
if( $_GET["_method"] == "delete" ) {
if( $_GET["file"][0] !== '.' ) {
$file = $path.$_GET["file"];
if( is_file( $file ) ) {
unlink( $file );
}
}
echo json_encode( true );
}
} else {
$model = new Photo;
$model->file = CUploadedFile::getInstance( $model, 'file' );
//We check that the file was successfully uploaded
if( $model->file !== null ) {
//Grab some data
$model->mime_type = $model->file->getType( );
//$model->size = $model->file->getSize( );
$model->name = $model->file->getName( );
//(optional) Generate a random name for our file
$filename = md5( Yii::app( )->user->id.microtime( ).$model->name);
$filename .= ".".$model->file->getExtensionName( );
if( $model->validate( ) ) {
//Move our file to our temporary dir
$model->file->saveAs( $path.$filename );
chmod( $path.$filename, 0777 );
//$model -> path = "/images/uploads/".$filename;
//here you can also generate the image versions you need
//using something like PHPThumb
//Now we need to save this path to the user's session
if( Yii::app( )->user->hasState( 'images' ) ) {
$userImages = Yii::app( )->user->getState( 'images' );
} else {
$userImages = array();
}
$userImages[] = array(
"path" => $path.$filename,
//the same file or a thumb version that you generated
"thumb" => $path.$filename,
"filename" => $filename,
'size' => $model->size,
'mime' => $model->mime_type,
'name' => $model->name,
);
Yii::app( )->user->setState( 'images', $userImages );
//Now we need to tell our widget that the upload was succesfull
//We do so, using the json structure defined in
// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
echo json_encode( array( array(
"name" => $model->name,
"type" => $model->mime_type,
"size" => $model->size,
"url" => $publicPath.$filename,
"thumbnail_url" => $publicPath."thumbs/$filename",
"delete_url" => $this->createUrl( "upload", array(
"_method" => "delete",
"file" => $filename
) ),
"delete_type" => "POST"
) ) );
} else {
//If the upload failed for some reason we log some data and let the widget know
echo json_encode( array(
array( "error" => $model->getErrors( 'file' ),
) ) );
Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ),
CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction"
);
}
} else {
throw new CHttpException( 500, "Could not upload file" );
}
}
}
和模型;
<?php
class Photo extends CFormModel
{
public $file;
public $mime_type;
public $size;
public $name;
public $filename;
public function tableName()
{
return 'photo';
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function rules()
{
return array(
array('file', 'file', 'types'=>'jpg,gif,html'),
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'file'=>'Upload files',
);
}
public function getReadableFileSize($retstring = null) {
// adapted from code at http://aidanlister.com/repos/v/function.size_readable.php
$sizes = array('bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
if ($retstring === null) { $retstring = '%01.2f %s'; }
$lastsizestring = end($sizes);
foreach ($sizes as $sizestring) {
if ($this->size < 1024) { break; }
if ($sizestring != $lastsizestring) { $this->size /= 1024; }
}
if ($sizestring == $sizes[0]) { $retstring = '%01d %s'; } // Bytes aren't normally fractional
return sprintf($retstring, $this->size, $sizestring);
}
/**
* A stub to allow overrides of thumbnails returned
* @since 0.5
* @author acorncom
* @return string thumbnail name (if blank, thumbnail won't display)
*/
public function getThumbnailUrl($publicPath) {
return $publicPath.$this->filename;
}
public function afterSave()
{
$this->addPhotos();
parent::afterSave();
}
public function addPhotos()
{
if(Yii::app()->user->hasState('images')){
$userImages = Yii::app()->user->getState('images');
$path = Yii::app()->getBasePath."/../images/uploads/";
if(!is_dir($path)){
mkdir($path);
chmod($path, 0777);
}
foreach($userImages as $image){
if(is_file($image['path'])){
if(rename($image['path'], $path.$image['filename'])){
chmod($path.$image['filename'], 0777);
$photo = new Photo;
//$photo -> size = $image['size'];
//$photo -> mime = $image['mime'];
$photo ->name = $image['name'];
$photo -> path = "/images/uploads/".$image['filename'];
if(!$photo->save()){
Yii::log(("Can't Save: \n").CVarDumper::dumpAsString($photo->getErrors()),CLogger::LEVEL_ERROR);
throw new Exception( "Could not save Image");
}
}
}
else{
Yii::log($image['path']."is not a file", CLogger::LEVEL_WARNING);
}
}
Yii::app()->user->setState('images', null);
}
}
}
答案 0 :(得分:1)
事实证明,如果我使用Active Record或查询生成器,它就不起作用。所以我使用了SQL并且它有效。这是代码:
public function actionPost( ) {
//Here we define the paths where the files will be stored temporarily
$path = Yii::app() -> getBasePath() . "/../images/";
$publicPath = Yii::app()->getBaseUrl( )."/images/";
//This is for IE which doens't handle 'Content-type: application/json' correctly
header( 'Vary: Accept' );
if( isset( $_SERVER['HTTP_ACCEPT'] )
&& (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) {
header( 'Content-type: application/json' );
} else {
header( 'Content-type: text/plain' );
}
//Here we check if we are deleting and uploaded file
if( isset( $_GET["_method"] ) ) {
if( $_GET["_method"] == "delete" ) {
if( $_GET["file"][0] !== '.' ) {
$query = "DELETE FROM `fuck`.`photo` WHERE `photo`.`path` = $file";
$file = $path.$_GET["file"];
if( is_file( $file ) ) {
unlink( $file );
Yii::app()->db->createCommand($query)->execute();
}
}
echo json_encode( true );
}
} else {
$model = new Photo;
$model->file = CUploadedFile::getInstance( $model, 'file' );
//We check that the file was successfully uploaded
if( $model->file !== null ) {
//Grab some data
$model->mime_type = $model->file->getType( );
$model->size = $model->file->getSize( );
$model->name = $model->file->getName( );
//(optional) Generate a random name for our file
$filename = md5( Yii::app( )->user->id.microtime( ).$model->name);
$filename .= ".".$model->file->getExtensionName( );
if( $model->validate( ) ) {
//Move our file to our temporary dir
$model->file->saveAs( $path.$filename );
chmod( $path.$filename, 0777 );
$drive = "/images/".$filename;
/* $db->createCommand()->insert('photo', array(
//'id'=>$newID,
'name'=>$model->name,
'path'=>$drive,
)); */
$sql = "INSERT INTO `gallery`.`photo` (
`name` ,
`path`
)
VALUES (
'$model->name', '$drive'
);
";
Yii::app()->db->createCommand($sql)->execute();
echo json_encode( array( array(
"name" => $model->name,
"type" => $model->mime_type,
"size" => $model->size,
"url" => $publicPath.$filename,
"thumbnail_url" => $publicPath."thumbs/$filename",
"delete_url" => $this->createUrl( "upload", array(
"_method" => "delete",
"file" => $filename
) ),
"delete_type" => "POST"
) ) );
} else {
//If the upload failed for some reason we log some data and let the widget know
echo json_encode( array(
array( "error" => $model->getErrors( 'file' ),
) ) );
Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ),
CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction"
);
}
} else {
throw new CHttpException( 500, "Could not upload file" );
}
}
}