This article mainly introduces the example of Yii2.0 integrating Alibaba Cloud oss to upload a single file. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
The previous article has introduced how to integrate Alibaba Cloud oss. This article mainly introduces uploading files to Alibaba Cloud oss.
Main idea: First, the files must be uploaded to the server, and then the files in the server should be transferred to Alibaba Cloud oss. After success, the file information will be written to the database. If it fails, the server files will be deleted.
Main steps:
0 Introduce several oss concepts.
accessKeyId ==>> It can be understood as the account number for accessing Alibaba Cloud OSS
accessKeySecret ==>> It can be understood as the password for accessing Alibaba Cloud OSS
bucket ==>> It can be understood as the root directory where the file is saved
endPoint ==>> Put it between the space and ossfile to form the url path for accessing the file, and also to obtain Ali Cloud pictures way.
object ==>> After your file is transferred to Alibaba Cloud oss, what is the path and what is its name?
It is easier to understand by looking at the screenshot:
1 File uploading still involves mvc. This time we start from the view, which mainly displays a form for submitting files. The aliyunoss.php code is as follows:
<?php use yii\widgets\ActiveForm; ?> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?> <?= $form->field($model, 'files')->fileInput() ?> <button>Submit</button> <?php ActiveForm::end() ?>
2 Receive the file in the controller and transfer it to the model for processing. The sample code of UploadController is as follows:
public function actionTestAliyun() { $model = new UploadForm(); // 实例化上传类 if (Yii::$app->request->isPost) { $model->files = UploadedFile::getInstance($model,'files'); //使用UploadedFile的getInstance方法接收单个文件 $model->setScenario('upload'); // 设置upload场景 $res = $model->uploadfile(); //调用model里边的upload方法执行上传 $err = $model->getErrors(); //获取错误信息 echo "<pre class="brush:php;toolbar:false">"; print_r($res); //打印上传结果 print_r($err); //打印错误信息,方便排错 exit; } return $this->render('aliyunoss',['model'=>$model]); }
3 When the controller transfers the image to the model file UploadForm.php, it must first move the file to the upload directory of the server, and then Move to Alibaba Cloud. The code is as follows:
<?php /** * Created by PhpStorm. * Description: 阿里oss上传图片 * Author: Weini * Date: 2016/11/17 0017 * Time: 上午 11:34 */ namespace app\models; use Yii; use yii\base\Exception; use yii\base\Model; class UploadForm extends Model { public $files; //用来保存文件 public function scenarios() { return [ 'upload' => ['files'], // 添加上传场景 ]; } public function rules(){ return [ [['files'],'file', 'skipOnEmpty' => false, 'extensions' => 'jpg, png, gif', 'mimeTypes'=>'image/jpeg, image/png, image/gif', 'maxSize'=>1024*1024*10, 'maxFiles'=>1, 'on'=>['upload']], //设置图片的验证规则 ]; } /** * 上传单个文件到阿里云 * @return boolean 上传是否成功 */ public function uploadfile(){ $res['error'] = 1; if ($this->validate()) { $uploadPath = dirname(dirname(__FILE__)).'/web/uploads/'; // 取得上传路径 if (!file_exists($uploadPath)) { @mkdir($uploadPath, 0777, true); } $ext = $this->files->getExtension(); // 获取文件的扩展名 $randnums = $this->getrandnums(); // 生成一个随机数,为了重命名文件 $imageName = date("YmdHis").$randnums.'.'.$ext; // 重命名文件 $ossfile = 'file/'.date("Ymd").'/'.$imageName; // 这里是保存到阿里云oss的文件名和路径。如果只有文件名,就会放到空间的根目录下。 $filePath = $uploadPath.$imageName; // 生成文件的绝对路径 if ($this->files->saveAs($filePath)){ // 上传文件到服务器 $filedata['filename'] = $imageName; // 准备图片信息,保存到数据库 $filedata['filePath'] = $filePath; // 准备图片信息,保存到数据库 $filedata['ossfile'] = $ossfile; // 准备图片信息,保存到数据库 $filedata['userid'] = Yii::$app->user->id; // 准备图片信息,保存到数据库,这个字段必须要,以免其他用户恶意删除别人的图片 $filedata['uploadtime'] = time(); // 准备图片信息,保存到数据库 // 上边这些代码不能照搬,要根据你项目的需求进行相应的修改。反正目的就是记录上传文件的信息 // 老板,这些代码是我搬来的,没仔细看,如果出问题了,你就扣我的奖金吧^_^ $trans = Yii::$app->db->beginTransaction(); // 开启事务 try{ $savefile = Yii::$app->db->createCommand()->insert('file', $filedata)->execute(); //把文件的上传信息写入数据库 $newid = Yii::$app->db->getLastInsertID(); //获取新增文件的id,用于返回。 if ($savefile) { // 如果插入数据库成功 $ossupload = Yii::$app->Aliyunoss->upload($ossfile, $filePath); //调用Aliyunoss组件里边的upload方法把文件上传到阿里云oss if ($ossupload) { // 如果上传成功, $res['error'] = 0; // 准备返回信息 $res['fileid'] = $newid; // 准备返回信息 $res['ossfile'] = $ossfile; // 准备返回信息 $trans->commit(); // 提交事务 } else { // 如果上传失败 unlink($filePath); // 删除服务器上的文件 $trans->rollBack(); // 事务回滚 } } unlink($filePath); // 插入数据库失败,删除服务器上的文件 $trans->rollBack(); // 事务回滚 } catch(Exception $e) { // 出了异常 unlink($filePath); // 删除服务器上的文件 $trans->rollBack(); // 事务回滚 } } } return $res; // 返回上传信息 } /** * 生成随机数 * @return string 随机数 */ protected function getrandnums() { $arr = array(); while (count($arr) < 10) { $arr[] = rand(1, 10); $arr = array_unique($arr); } return implode("", $arr); } }
If you encounter an error saying that no files are uploaded, it is most likely because the image verification rule setting maxFiles is greater than 1. Just change it to 1.
Please note that the above code will report a curl connection timeout error in the local test environment, but there is no problem when running on the server.
The above is the detailed content of Example of uploading a single file to yii2.0 oss. For more information, please follow other related articles on the PHP Chinese website!