Сохранить «Имя пользователя» как имя файла - PullRequest
1 голос
/ 29 марта 2012

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

Я использую Image Uploader от Aurigma, и чтобы сохранить загруженные изображения, я собрал этот скрипт вместе.

<?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();
  $userid = $packageFields["userid"];
  $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);
  }

  $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('userid', $userid);
  $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();
?>

Я хотел бы заменить элемент files имени файла и заменить его на username, чтобы каждая сохраненная папка и связанные файлы могли быть идентифицированы для каждого пользователя.

Я добавил текстовое поле имени пользователя в форму, которую этот скрипт сохраняет из

Думаю, я прав, говоря, что эту строку нужно изменить $descriptions->save($absGalleryPath . 'files.xml');.

Так что среди многих попыток я пытался изменить это на $descriptions->save($absGalleryPath . '$username.xml, $descriptions->save($absGalleryPath . $username '.xml, но ни одна из них не сработала, поэтому я не совсем уверен, что мне нужно изменить.

Мне просто интересно, может ли кто-нибудь взглянуть на это, пожалуйста, и дайте мне знать, где я ошибаюсь.

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

1 Ответ

0 голосов
/ 29 марта 2012

'$ username.xml' будет интерпретироваться как $ username.xml, вам нужно использовать "$ username.xml".Одинарные кавычки «отключают» использование переменной внутри строк.

То, что вы пытаетесь сделать, может быть плохой идеей, так как вы делаете так, чтобы имя пользователя не могло содержать «специальных символов», таких как «/».Возможно, это не проблема, если у вас уже есть правило, которое запрещает "/" быть частью имени пользователя.

...