可以使用yii2-webuploader扩展组件,图片上传so easy
扩展包:
"bailangzhan/yii2-webuploader": "dev-master"
后端图片文件处理代码:
UploadForm.php 用于验证上传的文件
use yii\base\Model;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;
/**
* Class UploadForm
* @package frontend\models
* @property UploadedFile $imageFile 图片文件
*/
class UploadForm extends Model
{
/**
* @var UploadedFile
*/
public $imageFile;
public $savePath;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png,jpg,jpeg']
];
}
public function upload()
{
if ($this->validate()) {
$relativePath = 'statics/upload/';
$fileMd5 = md5_file($this->imageFile->tempName);
!is_dir($relativePath) && FileHelper::createDirectory($relativePath);
$this->savePath = $relativePath . $fileMd5 . '.' . $this->imageFile->extension;
return $this->imageFile->saveAs($this->savePath);
} else {
return false;
}
}
}控制器代码:
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFile = UploadedFile::getInstanceByName('file');
if ($model->upload()) {
return Json::htmlEncode([
'code' => 0,
'url' => Yii::$app->params['domain'] . $model->savePath,
'attachment' => $model->savePath,
]);
}
return Json::htmlEncode([
'code' => 1,
'msg' => '上传失败:' . $model->getErrors()['file'][0]
]);
}
}