ProcessWire使用API上传多个文件
本实例以上传图片为例
前端表单配置
注意这里name
是数组格式images[]
,如果不是[]只能传递一个文件到服务端,此外还有注意multiple
的设置。
<input type="file" name='images[]' multiple="multiple" accept=".png, .jpg, .jpeg, .gif">
后端服务端的处理
// GET NAME $name = $input->post->name; $p_name = $sanitizer->pageName(time() . '-' . $name); // START CREATING PAGE $p = new Page(); // TEMPLATE TO SAVE ITEM $p->template = "contact-item"; // Parent Page $p->parent = $pages->get("/contact/"); // TURN OFF OUTPUT FORMATTING, IF IT'S ON $p->of(false); // START SAVING INPUT FIELDS $p->title = $name; $p->name = $p_name; // Page Save $p->save(); // UPLOAD IMAGES ( If input images was submitted ) if ($_FILES['images']['name'][0] == true) { // Set Maximum Files $max_files = 3; // Find Created Page id $get_id = pages()->get("name=$p_name"); // Final destination Folder $upload_path = $pages->get($get_id->id)->images->path; // Instantiate the class and give it the name of the HTML field $p_images = new WireUpload('images'); // Tell it to only accept 3 file $p_images->setMaxFiles($max_files); // Set Max File Size to 1MB or 2MB => (1024*1024*2) $p_images->setMaxFileSize(1024*1024); // Tell it to rename rather than overwrite existing files $p_images->setOverwrite(false); // have it put the files in their final destination. this should be okay since // The WireUpload class will only create PW compatible filenames $p_images->setDestinationPath($upload_path); // Tell it what extensions to expect $p_images->setValidExtensions(array('jpg', 'jpeg', 'png', 'gif')); // Execute upload and check for errors $files = $p_images->execute(); // Run a count($files) test to make sure there are actually files; if so, proceed; if not, generate getErrors() if(!count($files)) { $err = __("Sorry, but you need to add a Photo File like ( 'jpg', 'jpeg', 'png', 'gif' ) !!! ... Max Size ( 1MB ) !!!"); // ADD SOME SESSION MESSAGE $session->info = "<div class='alert-d'><h1>{$err}</h1></div>"; // TRASH OR DELETE FILE IF NOT EXSIST IMG FILE // $pages->delete($get_id); // Or Only Trash $pages->trash($get_id); // Redirect $session->redirect('./'); } // Check If To Many Files if( count($_FILES['images']['name']) > $max_files ) { $err = __("To Many Images ( MAX 3 Image ) !!! "); // ADD SOME SESSION MESSAGE $session->info = "<div class='alert-d'><h1>{$err}</h1></div>"; // TRASH OR DELETE FILE IF NOT EXSIST IMG FILE // $pages->delete($get_id); // OR Only Trash $pages->trash($get_id); // Redirect $session->redirect('./'); } // turn off output formatting, if it's on $p->of(false); // SET IMAGES VALUE foreach ($files as $file) { // $item .= $upload_path.$file . ','; // SET IMAGES FIELD $p->set("images",$file); } // SAVE IMAGE **************** / $p->save(); // SUCCESS MESSAGE $success = __("Congratulations, you've added Pictures"); // ADD SOME SESSION MESSAGE $session->info = "<div class='succes-m'><h1>{$success}</h1></div>"; // Redirect $session->redirect('./'); }