我在使用Yii2在postgresql中上传多个文件名时遇到问题,我有一个名为“i006t_factura”的表,其中有一个iD,一个名为“id_obra”的外键和一个“ruta”,这是我要保存的地方图像文件,但如果我有多个文件,那么我必须为“id_obra”保存多个名称,所以这是我的模型的代码:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "i006t_factura".
*
* @property integer $id
* @property integer $id_obra
* @property string $ruta
*
* @property C004tObraSocial $idObra
*/
class Factura extends \yii\db\ActiveRecord
{
public $ruta;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'i006t_factura';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id'], 'required'],
[['id_obra'], 'required'],
[['id_obra'], 'integer'],
[['ruta'], 'safe'],
[['ruta'], 'file', 'extensions'=>'jpg, gif, png',
'maxFiles' => 8,],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id_obra' => 'Id Obra',
'ruta' => 'Ruta',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getIdObra()
{
return $this->hasOne(C004tObraSocial::className(), ['id' => 'id_obra']);
}
public function afterSave($insert, $changedAttributes)
{
if(isset($this->ruta)){
$this->ruta=UploadedFiles::getInstance($this,'ruta');
if(is_object($this->ruta)){
$path=Yii::$app->basePath . '/archivos/'; //set directory path to save image
$this->ruta->saveAs($path.$this->id_obra."_".$this->ruta); //saving img in folder
$this->ruta = $this->id_obra."_".$this->ruta; //appending id to image name
\Yii::$app->db->createCommand()
->update('organization', ['ruta' => $this->ruta], 'id = "'.$this->id_obra.'"')
->execute(); //manually update image name to db
}
}
}
}
我的控制器
<?php
namespace app\controllers;
use Yii;
use app\models\Factura;
use app\models\FacturaSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* FacturaController implements the CRUD actions for Factura model.
*/
class FacturaController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Factura models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new FacturaSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Factura model.
* @param integer $id
* @param integer $id_obra
* @return mixed
*/
public function actionView($id_obra)
{
return $this->render('view', [
'model' => $this->findModel($id_obra),
]);
}
/**
* Creates a new Factura model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Factura();
if ($model->load(Yii::$app->request->post()) &&($model->save()) ) {
$model->ruta = UploadedFile::getInstances($model, 'ruta');
if($model->ruta){
$imagepath = 'archivos/'; // Create folder under web/uploads/logo
$model->ruta = $imagepath .rand(10,100).'-'.$model->ruta->name;
}
if($model->ruta){
$model->ruta->saveAs($model->ruta);
}
return $this->redirect(['view','id'=>$model->id, 'id_obra' => $model->id_obra]);
}else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Factura model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @param integer $id_obra
* @return mixed
*/
public function actionUpdate($id_obra)
{
$model = $this->findModel($id_obra);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->ruta = UploadedFile::getInstances($model, 'ruta');
if($model->file){
$imagepath = 'archivos/';
$model->ruta = $imagepath .rand(10,100).'-'.$model->ruta->name;
}
if($model->ruta){
$model->file->saveAs($model->logo);
return $this->redirect(['view','id'=>$model->id, 'id_obra' => $model->id_obra]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
public function actionDeleteimg($id_obra)
{
$ruta = Factura::find()-where(['id'=>$id_obra])->one()->ruta;
if($ruta){
if (!unlink($ruta)) {
return false;
}
}
$factura = Factura::findOne($id_obra);
$factura->ruta = NULL;
$factura->update();
return $this->redirect(['update', 'id_obra' => $id_obra]);
}
/**
* Deletes an existing Factura model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @param integer $id_obra
* @return mixed
*/
public function actionDelete($id,$id_obra)
{
$this->findModel($id)->delete();
$this->findModel($id_obra)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Factura model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @param integer $id_obra
* @return Factura the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id_obra)
{
if (($model = Factura::findOne(['id_obra' => $id_obra])) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
我的 _form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Factura */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="factura-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<?= $form->field($model, 'id')->textInput() ?>
<?= $form->field($model, 'id_obra')->textInput() ?>
<?= $form->field($model, "ruta[]")->fileInput( ['multiple'=>true])?>
<?php
if ($model->ruta) {
echo '<img src="'.\Yii::$app->request->BaseUrl.'/'.$model->ruta.'" width="90px"> ';
echo Html::a('Delete Logo', ['deleteimg', 'id'=>$model->id, 'field'=> 'ruta'], ['class'=>'btn btn-danger']).'<p>';
}
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
错误是当它想要上传图像时,“ruta”为空,因为它没有检测到URL,我不知道我的代码的某些部分是否需要迭代循环!
感谢您的回答!
答案 0 :(得分:0)
好吧,我解决了部分问题,即保存图片网址,但是对于一张图片!当我尝试将getInstances用于多个图像时,仍然有错误!
这是来自我的控制器的actionCreate():
public function actionCreate()
{
$model = new Factura();
if ($model->load(Yii::$app->request->post())) {
// Here is where I obtain the image
$model->file = UploadedFile::getInstance($model, 'file');
if($model->file){
$imagepath = 'archivos/';
$model->ruta = $imagepath .rand(10,100).'-'.$model->file->name;
}
if($model->save()){
if($model->file){
$model->file->saveAs($model->ruta);
}
return $this->redirect(['view', 'id' => $model->id, 'id_obra' => $model->id_obra]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
这是我更新的_form.php:
<div class="factura-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<?= $form->field($model, 'id')->textInput() ?>
<?= $form->field($model, 'id_obra')->textInput() ?>
//Where I submit my image
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
所以,仍有多个图像问题...不知道它与db表有关...