2012-04-10 2 views
0

Интересно, может ли кто-нибудь помочь мне.Вставка папок и файлов в PHP

Использование Aurigma Image Uploader Я собрал приведенный ниже код, который позволяет пользователям загружать изображения на основе местоположения.

<?php 

//This variable specifies relative path to the folder, where the gallery with uploaded files is located. 
//Do not forget about the slash in the end of the folder name. 
$galleryPath = 'UploadedFiles/'; 

require_once 'Includes/gallery_helper.php'; 

require_once 'ImageUploaderPHP/UploadHandler.class.php'; 

/** 
* FileUploaded callback function 
* @param $uploadedFile UploadedFile 
*/ 
function onFileUploaded($uploadedFile) { 

    $packageFields = $uploadedFile->getPackage()->getPackageFields(); 
    $username=$packageFields["username"]; 
    $locationid=$packageFields["locationid"]; 

    global $galleryPath; 

    $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR; 
    $absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR; 

    if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) { 
    initGallery($absGalleryPath, $absThumbnailsPath, FALSE); 
    } 

    $locationfolder = $_POST['locationid']; 
    $locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $locationfolder); 
    if (!is_dir($absGalleryPath . $locationfolder)) { 
    mkdir($absGalleryPath . $locationfolder, 0777); 
    } 

    $dirName = $_POST['folder']; 
    $dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $dirName); 
    if (!is_dir($absGalleryPath . $dirName)) { 
    mkdir($absGalleryPath . $dirName, 0777); 
    } 

    $path = rtrim($dirName, '/\\') . '/'; 

    $originalFileName = $uploadedFile->getSourceName(); 

    $files = $uploadedFile->getConvertedFiles(); 

    // save converter 1 

    $sourceFileName = getSafeFileName($absGalleryPath, $originalFileName); 
    $sourceFile = $files[0]; 
    /* @var $sourceFile ConvertedFile */ 
    if ($sourceFile) { 
    $sourceFile->moveTo($absGalleryPath . $sourceFileName); 
    } 

    // save converter 2 

    $thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName); 
    $thumbnailFile = $files[1]; 
    /* @var $thumbnailFile ConvertedFile */ 
    if ($thumbnailFile) { 
    $thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName); 
    } 

    //Load XML file which will keep information about files (image dimensions, description, etc). 
    //XML is used solely for brevity. In real-life application most likely you will use database instead. 
    $descriptions = new DOMDocument('1.0', 'utf-8'); 
    $descriptions->load($absGalleryPath . 'files.xml'); 

    //Save file info. 
    $xmlFile = $descriptions->createElement('file'); 
    $xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName); 
    $xmlFile->setAttribute('source', $sourceFileName); 
    $xmlFile->setAttribute('size', $uploadedFile->getSourceSize()); 
    $xmlFile->setAttribute('originalname', $originalFileName); 
    $xmlFile->setAttribute('thumbnail', $thumbnailFileName); 
    $xmlFile->setAttribute('description', $uploadedFile->getDescription()); 
    //Add additional fields 
    $xmlFile->setAttribute('username', $username); 
    $xmlFile->setAttribute('locationid', $locationid); 
    $xmlFile->setAttribute('folder', $dirName); 
    $descriptions->documentElement->appendChild($xmlFile); 
    $descriptions->save($absGalleryPath . 'files.xml'); 
} 

$uh = new UploadHandler(); 
$uh->setFileUploadedCallback('onFileUploaded'); 
$uh->processRequest(); 
?> 

Этот код, в дополнение к оригинальному сценарию создает «местоположение» папку с его именем, производный от «locationid» значение.

Теперь я столкнулся с проблемой, с которой я просто не могу найти решение.

Когда пользователь добавляет изображение, исходное изображение, файл под названием «files.xml» и папка с названием «Эскизы», содержащие эскизную версию изображения, создаются и сохраняются в папке «Загруженные файлы».

То, что я пытаюсь сделать, это переместить выше перечисленные файлы в мою папку «местоположение», поэтому структура будет:

загруженных файлы (папки)

  • Расположения (вложенная), содержащий исходное изображение, «files.xml», папка изображений, содержащая и уменьшенное изображение

Я, конечно, не эксперти т в PHP, но я пытался следовать формату существующего кода, создающего:

$locationpath = $locationfolder 
$abslocationpath = realpath($locationpath) . DIRECTORY_SEPARATOR; 

Затем я попытался указать различные файлы и папки, которые я хочу, чтобы перейти к $abslocationpath, но это не работает. Я уверен, что ответ заключается в создании нового каталога, но я не понимаю, как это сделать.

Я просто задавался вопросом, может ли кто-нибудь, возможно, дать некоторые указания, как я могу создать соответствующий каталог и переместить файлы в новую структуру папок, которую я хочу создать.

Большое спасибо

ответ

0

Ваш код выглядит хорошо, однако, я не вижу, где вы делаете любые вызовы, которые на самом деле переместить что-нибудь на пути местах.

Я немного изменил ваш код. Пожалуйста, сначала просмотрите его, обратив внимание на прокомментированные строки и внесите соответствующие корректировки и сообщите мне, если он даст желаемые результаты:

require_once 'Includes/gallery_helper.php'; 
require_once 'ImageUploaderPHP/UploadHandler.class.php'; 
$galleryPath = 'UploadedFiles/'; 

function onFileUploaded($uploadedFile) { 
    global $galleryPath; 

    $packageFields = $uploadedFile->getPackage()->getPackageFields(); 
    $username=$packageFields["username"]; 
    $locationid=$packageFields["locationid"]; 
    $locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['locationid']); 
    $dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['folder']); 

    $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR . $locationfolder . DIRECTORY_SEPARATOR; 
    $absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR; 

    if (!is_dir($absGalleryPath)) mkdir($absGalleryPath, 0777, true); 
    chmod($absGalleryPath, 0777); 
    if (!is_dir($absGalleryPath . $dirName)) mkdir($absGalleryPath . $dirName, 0777, true); 
    chmod($absGalleryPath . $dirName, 0777); 

    if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) 
    initGallery($absGalleryPath, $absThumbnailsPath, FALSE); 

    $originalFileName = $uploadedFile->getSourceName(); 
    $files = $uploadedFile->getConvertedFiles(); 
    $sourceFileName = getSafeFileName($absGalleryPath, $originalFileName); 
    $sourceFile = $files[0]; 

    if ($sourceFile) $sourceFile->moveTo($absGalleryPath . $sourceFileName); 
    $thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName); 
    $thumbnailFile = $files[1]; 
    if ($thumbnailFile) $thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName); 

    $xmlFile = $descriptions->createElement('file'); 
    // <-- please check the following line 
    $xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName); 
    $xmlFile->setAttribute('source', $sourceFileName); 
    $xmlFile->setAttribute('size', $uploadedFile->getSourceSize()); 
    $xmlFile->setAttribute('originalname', $originalFileName); 
    $xmlFile->setAttribute('thumbnail', $thumbnailFileName); 
    $xmlFile->setAttribute('description', $uploadedFile->getDescription()); 
    $xmlFile->setAttribute('username', $username); 
    $xmlFile->setAttribute('locationid', $locationid); 
    $xmlFile->setAttribute('folder', $dirName); 

    $descriptions = new DOMDocument('1.0', 'utf-8'); 
    $descriptions->load($absGalleryPath . 'files.xml'); 
    $descriptions->documentElement->appendChild($xmlFile); 
    $descriptions->save($absGalleryPath . 'files.xml'); 
} 

$uh = new UploadHandler(); 
$uh->setFileUploadedCallback('onFileUploaded'); 
$uh->processRequest(); 
+0

Hi @Authman Apatira ничего себе! Это абсолютно нормально, и это работает. Большое вам спасибо за вашу помощь. С наилучшими пожеланиями – IRHM

+0

Рад, что я могу помочь –

+0

Привет @ Айтман Апатира, мне очень жаль беспокоить вас этим. Там всего одна часть отсутствует. Если вы посмотрите на мой исходный код, появилась папка, созданная в '$ dirName'. Я вижу, что вы добавляете это в xml-файл, но я не могу найти, где создается папка. Могли бы вы, возможно, дать некоторые рекомендации относительно того, где мне нужно включить это, пожалуйста. С уважением – IRHM

Смежные вопросы