2014-03-19 98 views
1

我現在用的是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"); 
    } 
} 
} 

and the model;

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

你調試代碼? – Sergey

+0

是的,我做了,沒有錯誤 – user3214137

+0

你可以顯示你的SQL命令路徑的文件? – Sergey

回答

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

} 
}