当我尝试上传图像时,出现 SyntaxError: Unexpected token < in JSON at position 0. The name of image saves in DB but image file(in web/uploads) 没有。我不知道为什么。请帮帮我。
这是我的视图中的鳕鱼(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>
...
来自控制器的代码
...
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,
]);
}
}
...
来自模型的代码
<?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;
}
}
}
你是说这个吗?它与 actionUpdate 位于同一目录中。 但我如何在视图(profile/update.php)中使用它?因为我尝试从视图(profile/update.php)更新图像并使用actionUpdate。也许还有其他方法可以做到这一点? ...
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,
]);
}
}
...
问题已更新
来自供应商/kartik-v/yii2-krajee-base/FileInput 的代码
<?php
/**
* @copyright Copyright © 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);
}
}
您似乎正在使用自定义输入小部件,该小部件会上传到不同的网址(/ uploads)。您没有显示此特定 /uploads 操作的代码。 需要更多信息。
顺便说一句,“<" in JSON looks like you are returning HTML instead of json. maybe you are throwing an exception. check it in your runtime/logs.
你必须改为 'uploadUrl' => Url::to(['/uploads']), 输入您要上传照片的操作地址 'uploadUrl' => 文件上传.php,