Upload images using AJAX in YII Framework
1. the code in the controller:
/*** Get ajax uploaded files. */public function actionGetAjax () {$ model = new Attachment (); // load the Attachment model // read the image upload domain and use the system Upload component to upload $ tmpFile = CUploadedFile :: getInstanceByName ('image'); // read the upload configuration file. my configuration is/uploads $ Directroy = Yii: app ()-> params ['uploadpath']; // create a file storage path $ y = date ('Y'); $ m = date ('M'); $ d = date ('D '); $ Directroy = $ Directroy. "/"; $ pathd = $ Directroy. $ y. "/". $ m. "/". $ d. "/"; // create a folder. you must add dirname (Yii: app ()-> BasePath). Otherwise, an error may occur. Tool: makedir (dirname (Yii :: app ()-> BasePath ). $ pathd); if (is_object ($ tmpFile) & get_class ($ tmpFile) === 'cuploadedfile') {$ filename = time (). rand (); // file Upload extension $ ext = $ tmpFile-> extensionName; if ($ ext = 'jpg '| $ ext = 'GIF' | $ ext = 'PNG') {$ big = $ pathd. $ filename. '-600. '. $ ext; // 310 thumbnail $ small = $ pathd. $ filename. '-310. '. $ ext; // 310 thumbnail $ thumb = $ pathd. $ filename. '-100. '. $ ext; // 100 thumbnail $ model-> zat_thumb = $ thumb; // Thumbnail} $ uploadfile = $ pathd. $ filename. '. '. $ ext; // saved path $ model-> zat_url = $ pathd. $ filename. '. '. $ ext; // rename $ model-> zat_file_name = $ filename. '. '. $ ext; // file name $ model-> zat_title = $ tmpFile-> name; // File Title $ model-> zat_file_type = $ tmpFile-> type; // File Type $ model-> zat_file_size = $ tmpFile-> size; // File size $ model-> zat_image = 2; $ model-> zat_ip = Yii: app () -> request-> userHostAddress; // Upload IP // print_r ($ uploadfile);} if ($ model-> save ()) {// save it to the server $ tmpFile-> saveAs (dirname (Yii: app ()-> BasePath ). $ uploadfile); if ($ ext = 'jpg '| $ ext = 'GIF' | $ ext = 'PNG ') {// use the image-Kohana image processing library extension $ img = Yii: app ()-> image-> load (dirname (Yii: app ()-> BasePath ). $ uploadfile); $ img-> resize (600,600)-> quality (85); $ img-> save (dirname (Yii: app ()-> BasePath ). $ big); // Generate a 600 thumbnail $ img-> resize (310,310)-> quality (85); $ img-> save (dirname (Yii: app () -> BasePath ). $ small); // Generate a 310 thumbnail $ img-> resize (100,100)-> quality (85); $ img-> save (dirname (Yii: app () -> BasePath ). $ thumb); // Generate 100 thumbnails} if ($ ext = 'jpg '| $ ext = 'GIF' | $ ext = 'PNG ') {$ str = json_encode (array ('upfile' => array ('Zat _ id' => Yii: app ()-> db-> getLastInsertID (), // Insert ID 'file' => $ uploadfile, // the source image 'small' => $ small, // 310 thumbnail 'thumb' => $ thumb, // 100 thumbnail);} else {$ str = json_encode (array ('upfile' => array ('Zat _ id' => Yii: app () -> db-> getLastInsertID (), 'file' => $ uploadfile,);} echo $ str ;}}
2. View code:
3. js code: