2016-08-07 48 views
0

Wenn ich versuche, ein Bild hochzuladen, habe ich SyntaxError: Unerwartetes Token < in JSON an Position 0. Der Name des Bildes speichert in der DB aber Bilddatei (im Web/Uploads) nicht. Ich weiß nicht warum. Hilf mir bitte. enter image description hereFehler beim Hochladen des Bildes in yii2 (SyntaxError: Unerwartetes Token <in JSON an Position 0)

hier ist mein Kabeljau aus der Sicht (update.php)

...  
<div class="user-form"> 

      <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multi-part/form-data']]); ?> 

      <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?> 
      <?= $form->field($model, 'usersurname')->textInput(['maxlength' => true]) ?> 
      <?= $form->field($model, 'age')->textInput() ?> 
      <?= $form->field($model, 'img')->widget(FileInput::classname(), [ 
       'options' => ['accept'=>'image/*'], 
       'pluginOptions'=>[ 
        'uploadUrl' => Url::to(['/uploads']), 
        'allowedFileExtensions'=>['jpg', 'gif', 'png'], 
        'showUpload' => true, 
        'initialPreview' => [ 
    //     $model-> img ? Html::img($model-> img) : null, // checks the models to display the preview 
        ], 
        'overwriteInitial' => false, 
       ], 
      ]); ?> 

      <div class="form-group"> 
       <?= Html::submitButton(Yii::t('app', 'BUTTON_SAVE'), ['class' => 'btn siteColor']) ?> 
      </div> 

      <?php ActiveForm::end(); ?> 

     </div> 
... 

Code von der Steuerung

... 
    public function actionUpdate() 
    { 
     $user = $this->findModel(); 
     $model = new ProfileUpdateForm($user); 
     if ($model->load(Yii::$app->request->post()) && $model->update()) { 
      return $this->redirect(['index']); 
     } else { 
      return $this->render('update', [ 
       'model' => $model, 
      ]); 
     } 

    } 
... 

Code von Modell

<?php 

namespace app\modules\user\models; 

use yii\base\Model; 
use Yii; 



class ProfileUpdateForm extends Model 
{ 
    public $email; 
    public $username; 
    public $usersurname; 
    public $data; 
    public $age; 
    public $from; 
    public $time; 
    public $img; 
    public $file; 

    /** 
    * @var User 
    */ 
    private $_user; 

    public function __construct(User $user, $config = []) 
    { 
     $this->_user = $user; 
     parent::__construct($config); 
    } 

    public function init() 
    { 
     $this->email = $this->_user->email; 
     $this->username = $this->_user->username; 
     $this->usersurname = $this->_user->usersurname; 
     $this->img = $this->_user->img; 
//  $this-> file = $this->_user-> file; 
     parent::init(); 
    } 

    public function rules() 
    { 
     return [ 
      ['email', 'required'], 
      ['email', 'email'], 
      [ 
       'email', 
       'unique', 
       'targetClass' => User::className(), 
       'message' => Yii::t('app', 'ERROR_EMAIL_EXISTS'), 
       'filter' => ['<>', 'id', $this->_user->id], 
      ], 
      [['email','usersurname', 'username', 'img'], 'string', 'max' => 255], 
      [['img'], 'file', 'extensions' => 'png, jpg, gif'], 
      ['age', 'integer'], 
     ]; 
    } 

    public function update() 
    { 
     if ($this->validate()) { 
      $user = $this->_user; 
      $user->email = $this->email; 
      $user->username = $this->username; 
      $user-> age = $this -> age; 
      return $user->save(); 
     } else { 
      return false; 
     } 
    } 

} 

Sie dies bedeuten, ? Es befindet sich im selben Verzeichnis mit actionUpdate. Aber wie kann ich es in der Ansicht verwenden (profile/update.php)? 'Coz ich versuche, das Bild von der Ansicht (Profil/update.php) zu aktualisieren und actionUpdate zu verwenden. Vielleicht gibt es andere Möglichkeiten, es zu tun? ...

public function actionUpload() 
    { 
     $user = $this->findModel(); 
     $model = new User($user); 
     if ($model->load(Yii::$app->request->post()) && $model->update()) { 
      $imageName = rand(1000,100000); 
      $model->file = UploadedFile::getInstance($model, 'file'); 

      $model->img =''.$imageName.'.'.$model->file->extension; //тут возникает ошибка Trying to get property of non-object 
      $model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension); 
      $model->file = null; 
      $model->save(); 
      return $this->redirect(['index']); 
     } else { 
      return $this->render('update', [ 
       'model' => $model, 
      ]); 
     } 
    } 
... 

FRAGE AKTUALISIERT
Code von Verkäufer/kartik-v/yii2-krajee-base/FileInput-

<?php 

/** 
* @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2016 
* @package yii2-widgets 
* @subpackage yii2-widget-fileinput 
* @version 1.0.5 
*/ 

namespace kartik\file; 

use Yii; 
use yii\helpers\ArrayHelper; 
use yii\helpers\Html; 
use kartik\base\InputWidget; 
use kartik\base\TranslationTrait; 

/** 
* Wrapper for the Bootstrap FileInput JQuery Plugin by Krajee. The FileInput widget is styled for Bootstrap 3.0 with 
* ability to multiple file selection and preview, format button styles and inputs. Runs on all modern browsers 
* supporting HTML5 File Inputs and File Processing API. For browser versions IE9 and below, this widget will 
* gracefully degrade to normal HTML file input. 
* 
* @see http://plugins.krajee.com/bootstrap-fileinput 
* @see https://github.com/kartik-v/bootstrap-fileinput 
* 
* @author Kartik Visweswaran <[email protected]> 
* @since 2.0 
* @see http://twitter.github.com/typeahead.js/examples 
*/ 
class FileInput extends InputWidget 
{ 
    use TranslationTrait; 

    /** 
    * @var bool whether to resize images on client side 
    */ 
    public $resizeImages = false; 

    /** 
    * @var bool whether to load sortable plugin to rearrange initial preview images on client side 
    */ 
    public $sortThumbs = true; 

    /** 
    * @var bool whether to load dom purify plugin to purify HTML content in purfiy 
    */ 
    public $purifyHtml = true; 

    /** 
    * @var bool whether to show 'plugin unsupported' message for IE browser versions 9 & below 
    */ 
    public $showMessage = true; 

    /* 
    * @var array HTML attributes for the container for the warning 
    * message for browsers running IE9 and below. 
    */ 
    public $messageOptions = ['class' => 'alert alert-warning']; 

    /** 
    * @var array the internalization configuration for this widget 
    */ 
    public $i18n = []; 

    /** 
    * @inheritdoc 
    */ 
    public $pluginName = 'fileinput'; 

    /** 
    * @var array the list of inbuilt themes 
    */ 
    private static $_themes = ['fa', 'gly']; 

    /** 
    * @var array initialize the FileInput widget 
    */ 
    public function init() 
    { 
     parent::init(); 
     $this->_msgCat = 'fileinput'; 
     $this->initI18N(__DIR__); 
     $this->initLanguage(); 
     $this->registerAssets(); 
     if ($this->pluginLoading) { 
      Html::addCssClass($this->options, 'file-loading'); 
     } 
     $input = $this->getInput('fileInput'); 
     $script = 'document.getElementById("' . $this->options['id'] . '").className.replace(/\bfile-loading\b/,"");'; 
     if ($this->showMessage) { 
      $validation = ArrayHelper::getValue($this->pluginOptions, 'showPreview', true) ? 
       Yii::t('fileinput', 'file preview and multiple file upload') : 
       Yii::t('fileinput', 'multiple file upload'); 
      $message = '<strong>' . Yii::t('fileinput', 'Note:') . '</strong> ' . 
       Yii::t(
        'fileinput', 
        'Your browser does not support {validation}. Try an alternative or more recent browser to access these features.', 
        ['validation' => $validation] 
       ); 
      $content = Html::tag('div', $message, $this->messageOptions) . "<script>{$script};</script>"; 
      $input .= "\n" . $this->validateIE($content); 
     } 
     echo $input; 
    } 

    /** 
    * Validates and returns content based on IE browser version validation 
    * 
    * @param string $content 
    * @param string $validation 
    * 
    * @return string 
    */ 
    protected function validateIE($content, $validation = 'lt IE 10') 
    { 
     return "<!--[if {$validation}]><br>{$content}<![endif]-->"; 
    } 

    /** 
    * Registers the asset bundle and locale 
    */ 
    public function registerAssetBundle() 
    { 
     $view = $this->getView(); 
     if ($this->resizeImages) { 
      CanvasBlobAsset::register($view); 
      $this->pluginOptions['resizeImage'] = true; 
     } 
     $theme = ArrayHelper::getValue($this->pluginOptions, 'theme'); 
     if (!empty($theme) && in_array($theme, self::$_themes)) { 
      FileInputThemeAsset::register($view)->addTheme($theme); 
     } 
     if ($this->sortThumbs) { 
      SortableAsset::register($view); 
     } 
     if ($this->purifyHtml) { 
      DomPurifyAsset::register($view); 
      $this->pluginOptions['purifyHtml'] = true; 
     } 
     FileInputAsset::register($view)->addLanguage($this->language, '', 'js/locales'); 
    } 

    /** 
    * Registers the needed assets 
    */ 
    public function registerAssets() 
    { 
     $this->registerAssetBundle(); 
     $this->registerPlugin($this->pluginName); 
    } 
} 

Antwort

1

es scheint, dass Sie eine benutzerdefinierte Eingabe-Widgets verwenden, die Uploads auf eine andere URL (/ uploads). Sie haben den Code für diese spezifische/uploads-Aktion nicht angezeigt. benötigen weitere Informationen.

BTW, "<" in JSON sieht aus wie Sie HTML anstelle von JSON zurückgeben. Vielleicht werfen Sie eine Ausnahme. überprüfen Sie es in Ihren Runtime/logs.

+0

Danke für den Versuch zu helfen, ich habe Update-Frage. Ich verwende dieses https://github.com/kartik-v/yii2-widget-fileinput Widget. Und ich habe Code aus diesem Widget hinzufügen (von meinem Hersteller/kartik-v/yii2-krajee-base/FileInput) –

+1

Sie verstecken immer noch Ihre Controller-Aktion für die Handhabung von Uploads in "uploadUrl" => Url :: bis (['/site/file-upload ']), –

+0

Ich habe eine Update-Frage und füge actionUpload hinzu. Ich dachte, dass niemand mir helfen will. Danke. Mein Glaube ist noch am Leben) –