PHP Laravel uploads images, files, and other class packages,

Source: Internet
Author: User

PHP Laravel uploads images, files, and other class packages,

Today, the upload function in the project is encapsulated into a class, which is convenient for later use. It is a simple encapsulation, and I feel that it is not very good. I will continue to optimize it later.

The Code is as follows:

<? Php/*** Created by PhpStorm. * User: wady www.bcty365.com * Date: * Time: */namespace App \ ThinkClass; use Symfony \ Component \ HttpFoundation \ File \ UploadedFile; class UploadClass {/*** @ var UploadedFile $ file; */protected $ file;/*** upload error message * @ var string */private $ error = ''; // upload error message private $ fullPath = ''; // absolute address private $ config = array ('maxsize' => 3*1024*1024, // The size limit of the uploaded file (0 -Unlimited) 'exts' => array ('jpg ', 'jpeg', 'gif', 'png ', 'Doc', 'docx', 'xls ', 'xlsx', 'ppt ', 'ppt', 'pdf', 'rar ', 'zip'), // The file suffix 'subname' => '', // subdirectory creation method, [0]-function name, [1]-parameter, multiple parameters use array 'rootpath' => '/uploads /', // Save the root path 'savepath' => '', // Save the path 'thumb' => array (), // specifies the cropping compression ratio ); public function _ construct ($ config = array () {/* Get configuration */$ this-> config = array_merge ($ this-> config, $ config ); if (! Emptyempty ($ this-> config ['exts']) {if (is_string ($ this-> exts )) {$ this-> config ['exts'] = explode (',', $ this-> exts );} $ this-> config ['exts'] = array_map ('strlower ', $ this-> exts );} $ this-> config ['subname'] = $ this-> subName? Ltrim ($ this-> subName ,'/'):'/'. date ('ymmd'); $ this-> fullPath = rtrim (public_path (),'/'). $ this-> config ['rootpath'];} public function _ get ($ name) {return $ this-> config [$ name];} public function _ set ($ name, $ value) {if (isset ($ this-> config [$ name]) {$ this-> config [$ name] = $ value ;}} public function _ isset ($ name) {return isset ($ this-> config [$ name]);}/*** get the last upload error message * @ return string error message */p Ublic function getError () {return $ this-> error;} public function upload ($ file) {if (emptyempty ($ file )) {$ this-> error = 'file not uploaded '; return false;} if (! $ This-> checkRootPath ($ this-> fullPath) {$ this-> error = $ this-> getError (); return false ;} $ fileSavePath = $ this-> fullPath. $ this-> savePath. $ this-> subName; if (! $ This-> checkSavePath ($ fileSavePath) {$ this-> error = $ this-> getError (); return false;} $ files = array (); if (! Is_array ($ file) {// if it is not an array, convert it to an array $ files [] = $ file;} else {$ files = $ file;} $ info = array (); $ imgThumb = new \ App \ ThinkClass \ ThumbClass (); foreach ($ files as $ key = >$ f) {$ this-> file = $ f; $ f-> ext = strtolower ($ f-> getClientOriginalExtension ();/* File Upload check */if (! $ This-> check ($ f) {continue;} $ fileName = str_random (12 ). '. '. $ f-> ext;/* save the file and record the successfully saved file */if ($ this-> file-> move ($ fileSavePath, $ fileName )) {/* the image is compressed in High Aspect Ratio */\ Log: notice ($ fileSavePath. $ fileName); if (! Emptyempty ($ this-> thumb) & is_array ($ this-> thumb) {$ imgThumb-> thumb ($ this-> thumb, $ fileSavePath. '/'. $ fileName) ;}$ info [] = $ this-> rootPath. $ this-> savePath. $ this-> subName. '/'. $ fileName;} return is_array ($ info )? $ Info: false;}/*** check the root directory for uploading * @ param string $ rootpath root directory * @ return boolean true-check successful, false-check failed */protected function checkRootPath ($ rootpath) {if (! (Is_dir ($ rootpath) & is_writable ($ rootpath) {$ this-> error = 'the upload root directory does not exist! '; Return false;} return true;}/*** check upload directory * @ param string $ savepath upload directory * @ return boolean check result, true-pass, false-Failed */public function checkSavePath ($ savepath) {/* detect and create directory */if (! $ This-> mkdir ($ savepath) {return false;} else {/* check whether the directory can be written */if (! Is_writable ($ savepath) {$ this-> error = 'upload directory cannot be written! '; Return false;} else {return true ;}}/*** check the uploaded file * @ param array $ file information */private function check ($ file) {/* check the file size */if (! $ This-> checkSize ($ file-> getSize () {$ this-> error = 'size of the uploaded file does not match! '; Return false;}/* check the file suffix */if (! $ This-> checkExt ($ file-> ext) {$ this-> error = 'upload file suffix not allowed '; return false ;} /* Check */return true;}/*** to check whether the file size is valid * @ param integer $ size data */private function checkSize ($ size) {return! ($ Size> $ this-> maxSize) | (0 = $ this-> maxSize );} /*** check whether the uploaded file suffix is valid * @ param string $ ext suffix */private function checkExt ($ ext) {return emptyempty ($ this-> config ['exts'])? True: in_array (strtolower ($ ext), $ this-> exts );} /*** create directory ** @ param string $ savepath the Muli to be created * @ return boolean creation status, true-successful, false-Failed */protected function mkdir ($ savepath) {if (is_dir ($ savepath) {return true;} if (mkdir ($ savepath, 0777, true) {return true ;} else {$ this-> error = "Directory creation failed"; return false ;}}}

Use Case:

Reference the use App \ ThinkClass \ UploadClass in the header;

$upload = new UploadClass(); $upload->exts=array('jpg','png'); $upload->maxSize=5*1024*1024; $upload->savePath='course/uid_6'; $file = $request->file('fileImg'); $aa = $upload->upload($file); dd($aa);

Summary

The above is a small compilation of PHP Laravel image uploading and file encapsulation. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.