/** * 文件上传 * @param $dir * @return array */ public function upload($dir) { $model = new UploadForm(); $date_time = date('Ymd'); if (!file_exists($dir)) { mkdir($dir, 0775); } if (!file_exists($dir . "upload/")) { mkdir($dir . "upload/", 0775); } // 原图文件夹 if (!file_exists($dir . "upload/picture/")) { mkdir($dir . "upload/picture/", 0775); } if (!file_exists($dir . "upload/picture/" . $date_time . "/")) { mkdir($dir . "upload/picture/" . $date_time . '/', 0775); } // 缩略图文件夹 if (!file_exists($dir . "upload/thumb/")) { mkdir($dir . "upload/thumb/", 0775); } if (!file_exists($dir . "upload/thumb/" . $date_time . "/")) { mkdir($dir . "upload/thumb/" . $date_time . '/', 0775); } if (\Yii::$app->request->isPost) { $model->file = UploadedFile::getInstanceByName("file"); $fileTypes = array('jpg', 'jpeg', 'gif', 'png', 'bmp'); // File extensions if ($model->validate() && in_array($model->file->extension, $fileTypes)) { $time = time(); $rand = rand(1, 100000000); $file_name = $dir . "upload/picture/" . $date_time . '/' . $time . $rand . '.' . $model->file->extension; $model->file->saveAs($file_name, true); $fileInfo = getimagesize($file_name); $picInfo = $this->pictureRatio($fileInfo[0], $fileInfo[1]); if (rename($file_name, $dir . "upload/picture/" . $date_time . '/' . $time . $rand . '_' . $picInfo[0] . '_' . $picInfo[1] . '.' . $model->file->extension)) { return array('status' => 1, 'info' => '上传成功', 'path' => $date_time . '/' . $time . $rand . '_' . $picInfo[0] . '_' . $picInfo[1] . '.' . $model->file->extension, 'extension' => $model->file->extension, 'time' => $time); } } } return array('status' => -1, 'info' => '上传失败!~'); }
public function uploadFiles($attribute, $subfolder = '') { $savePath = array(); $model = new UploadForm('image', true); $model->file = UploadedFile::getInstancesByName($attribute); if ($model->file) { if ($model->validate()) { foreach ($model->file as $file) { // get the new name of file $newFileName = $file->baseName . '_' . time() . '.' . $file->extension; $file->saveAs(Yii::$app->params['uploadPath'] . $subfolder . '/' . $newFileName); $returnPath = $subfolder . '/' . $newFileName; $savePath[] = $returnPath; // create a thumbnail $thumbPath = $subfolder . '/thumb/thumb-' . $newFileName; Image::thumbnail(Yii::$app->params['uploadPath'] . $returnPath, $this->thumbWidth, $this->thumbHeight)->save(Yii::$app->params['uploadPath'] . $thumbPath, ['quality' => 80]); } } } return $savePath; }