Answer the question
In order to leave comments, you need to log in
How to upload a file to the server correctly and not get a 400 error?
Hello.
Trying to upload music to server .mp3
Model
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
class MusicUpload extends Model{
public $image;
public function rules()
{
return [
[['image'], 'required'],
// [['image'], 'file', 'extensions' => 'jpg,png']
];
}
public function uploadFile(UploadedFile $file, $currentImage)
{
$this->image = $file;
if($this->validate())
{
$this->deleteCurrentImage($currentImage);
return $this->saveImage();
}
}
private function getFolder()
{
return Yii::getAlias('@web') . 'uploads/musics/';
}
private function generateFilename()
{
return strtolower(md5(uniqid($this->image->baseName)) . '.' . $this->image->extension);
}
public function deleteCurrentImage($currentImage)
{
if($this->fileExists($currentImage))
{
unlink($this->getFolder() . $currentImage);
}
}
public function fileExists($currentImage)
{
if(!empty($currentImage) && $currentImage != null)
{
return file_exists($this->getFolder() . $currentImage);
}
}
public function saveImage()
{
$filename = $this->generateFilename();
$this->image->saveAs($this->getFolder() . $filename);
return $filename;
}
}
public function actionSetFile($id)
{
$model = new MusicUpload();
if (Yii::$app->request->isPost)
{
$article = $this->findModel($id);
$file = UploadedFile::getInstance($model, 'image');
if($article->saveFile($model->uploadFile($file, $article->path)))
{
return $this->redirect(['view', 'id'=>$article->id]);
}
}
return $this->render('music', ['model'=>$model]);
}
public function saveFile($filename)
{
$this->path = $filename;
return $this->save(false);
}
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'image')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Загрузить', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
Answer the question
In order to leave comments, you need to log in
Everything turned out to be quite simple - in the php settings it was necessary to increase the weight of the uploaded file :)
Replace:
with:
In the validator.
Well, it is desirable to replace the image name with a more suitable
one. You are trying to upload a file under the guise of an image and the validator checks whether it is an image or not.
Google suggested that the problem is probably in csrf tokens
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question