/**
  * Uploads a new file for the given FileField instance.
  *
  * @param string $name EAV attribute name
  * @throws \Cake\Network\Exception\NotFoundException When invalid slug is given,
  *  or when upload process could not be completed
  */
 public function upload($name)
 {
     $instance = $this->_getInstance($name);
     require_once Plugin::classPath('Field') . 'Lib/class.upload.php';
     $uploader = new \upload($this->request->data['Filedata']);
     if (!empty($instance->settings['extensions'])) {
         $exts = explode(',', $instance->settings['extensions']);
         $exts = array_map('trim', $exts);
         $exts = array_map('strtolower', $exts);
         if (!in_array(strtolower($uploader->file_src_name_ext), $exts)) {
             $this->_error(__d('field', 'Invalid file extension.'), 501);
         }
     }
     $response = '';
     $uploader->file_overwrite = false;
     $folder = normalizePath(WWW_ROOT . "/files/{$instance->settings['upload_folder']}/");
     $url = normalizePath("/files/{$instance->settings['upload_folder']}/", '/');
     $uploader->process($folder);
     if ($uploader->processed) {
         $response = json_encode(['file_url' => Router::url($url . $uploader->file_dst_name, true), 'file_size' => FileToolbox::bytesToSize($uploader->file_src_size), 'file_name' => $uploader->file_dst_name, 'mime_icon' => FileToolbox::fileIcon($uploader->file_src_mime)]);
     } else {
         $this->_error(__d('field', 'File upload error, details: {0}', $uploader->error), 502);
     }
     $this->viewBuilder()->layout('ajax');
     $this->title(__d('field', 'Upload File'));
     $this->set(compact('response'));
 }
 /**
  * test bytesToSize() method.
  *
  * @return void
  */
 public function testBytesToSize()
 {
     $this->assertEquals('6 B', FileToolbox::bytesToSize(6));
     $this->assertEquals('1 KB', FileToolbox::bytesToSize(1024));
     $this->assertEquals('3.6 MB', FileToolbox::bytesToSize(1024 * 1024 * 3.6));
     $this->assertEquals('1.66 GB', FileToolbox::bytesToSize(1024 * 1024 * 1024 * 1.66));
     $this->assertEquals('1.3 TB', FileToolbox::bytesToSize(1024 * 1024 * 1024 * 1024 * 1.3));
 }