2013-11-11 5 views
0

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

/** 
* Stores any image uploaded from the edit form 
* 
* @param assoc The 'image' element from the $_FILES array containing the file upload data 
*/ 

public function storeUploadedImage($image) { 

if ($image['error'] == UPLOAD_ERR_OK) 
{ 
    // Does the Article object have an ID? 
    if (is_null($this->id)) trigger_error("Article::storeUploadedImage(): Attempt to upload an image for an Article object that does not have its ID property set.", E_USER_ERROR); 

    // Delete any previous image(s) for this article 
    $this->deleteImages(); 

    // Get and store the image filename extension 
    $this->imageExtension = strtolower(strrchr($image['name'], '.')); 

    // Store the image 

    $tempFilename = trim($image['tmp_name']); 

    if (is_uploaded_file ($tempFilename)) { 
    if (!(move_uploaded_file($tempFilename, $this->getImagePath()))) trigger_error("Article::storeUploadedImage(): Couldn't move uploaded file.", E_USER_ERROR); 
    if (!(chmod($this->getImagePath(), 0666))) trigger_error("Article::storeUploadedImage(): Couldn't set permissions on uploaded file.", E_USER_ERROR); 
    } 

    // Get the image size and type 
    $attrs = getimagesize ($this->getImagePath()); 
    $imageWidth = $attrs[0]; 
    $imageHeight = $attrs[1]; 
    $imageType = $attrs[2]; 

    // Load the image into memory 
    switch ($imageType) { 
    case IMAGETYPE_GIF: 
     $imageResource = imagecreatefromgif ($this->getImagePath()); 
     break; 
    case IMAGETYPE_JPEG: 
     $imageResource = imagecreatefromjpeg ($this->getImagePath()); 
     break; 
    case IMAGETYPE_PNG: 
     $imageResource = imagecreatefrompng ($this->getImagePath()); 
     break; 
    default: 
     trigger_error ("Article::storeUploadedImage(): Unhandled or unknown image type ($imageType)", E_USER_ERROR); 
    } 

    // Copy and resize the image to create the thumbnail 
    $thumbHeight = intval ($imageHeight/$imageWidth * ARTICLE_THUMB_WIDTH); 
    $thumbResource = imagecreatetruecolor (ARTICLE_THUMB_WIDTH, $thumbHeight); 
    imagecopyresampled($thumbResource, $imageResource, 0, 0, 0, 0, ARTICLE_THUMB_WIDTH, $thumbHeight, $imageWidth, $imageHeight); 

    // Save the thumbnail 
    switch ($imageType) { 
    case IMAGETYPE_GIF: 
     imagegif ($thumbResource, $this->getImagePath(IMG_TYPE_THUMB)); 
     break; 
    case IMAGETYPE_JPEG: 
     imagejpeg ($thumbResource, $this->getImagePath(IMG_TYPE_THUMB), JPEG_QUALITY); 
     break; 
    case IMAGETYPE_PNG: 
     imagepng ($thumbResource, $this->getImagePath(IMG_TYPE_THUMB)); 
     break; 
    default: 
     trigger_error ("Article::storeUploadedImage(): Unhandled or unknown image type ($imageType)", E_USER_ERROR); 
    } 

    $this->update(); 
} 
} 


/** 
* Deletes any images and/or thumbnails associated with the article 
*/ 

public function deleteImages() { 

// Delete all fullsize images for this article 
foreach (glob(ARTICLE_IMAGE_PATH . "/" . IMG_TYPE_FULLSIZE . "/" . $this->id . ".*") as $filename) { 
    if (!unlink($filename)) trigger_error("Article::deleteImages(): Couldn't delete image file.", E_USER_ERROR); 
} 

// Delete all thumbnail images for this article 
foreach (glob(ARTICLE_IMAGE_PATH . "/" . IMG_TYPE_THUMB . "/" . $this->id . ".*") as $filename) { 
    if (!unlink($filename)) trigger_error("Article::deleteImages(): Couldn't delete thumbnail file.", E_USER_ERROR); 
} 

// Remove the image filename extension from the object 
$this->imageExtension = ""; 
} 


/** 
* Returns the relative path to the article's full-size or thumbnail image 
* 
* @param string The type of image path to retrieve (IMG_TYPE_FULLSIZE or IMG_TYPE_THUMB). Defaults to IMG_TYPE_FULLSIZE. 
* @return string|false The image's path, or false if an image hasn't been uploaded 
*/ 

public function getImagePath($type=IMG_TYPE_FULLSIZE) { 
return ($this->id && $this->imageExtension) ? (ARTICLE_IMAGE_PATH . "/$type/" . $this->id . $this->imageExtension) : false; 
} 
  1. Он загружает одно изображение и один эскиз в статье
  2. Переименовать файл (напр если идентификатор статьи базы данных равен 5, полный размер и уменьшенное изображение после переименования будут равны 5)

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

И мое второе намерение состоит в том, чтобы переименовать каждый файл в соответствии с заголовком статьи (например, если название статьи - Nokia N9, первое изображение при загрузке будет nokia_n9_1.jpg, второе будет nokia_n9_2.jpg, а левый также будет как 1-й и 2-й.

Я новичок в PHP OOP. Я знаю, что это очень много работы, и мы будем очень благодарны. Если вы хотите увидеть полный исходный код CMS, ссылка

http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/

http://www.elated.com/articles/add-image-uploading-to-your-cms/

ответ

0

На самом деле речь идет не о ООП, чтобы сделать это изменения):

Так admin.php у вас есть это:

// User has posted the article edit form: save the new article 
$article = new Article; 
$article->storeFormValues($_POST); 
$article->insert(); 
if (isset($_FILES['image'])) $article->storeUploadedImage($_FILES['image']); 
header("Location: admin.php?status=changesSaved"); 

Рассматривают читают эту http://www.php.net/manual/en/features.file-upload.post-method.php, чтобы понять изменения, мы сделали. Поэтому изменить администратора PHP для этого:

// User has posted the article edit form: save the new article 
    $article = new Article; 
    $article->storeFormValues($_POST); 
    $article->insert(); 
    if (isset($_FILES['image'])) $article->storeUploadedImage($_FILES['image'], '1'); 
    if (isset($_FILES['image2'])) $article->storeUploadedImage($_FILES['image2'], '2'); 
    if (isset($_FILES['image3'])) $article->storeUploadedImage($_FILES['image3'], '3'); 
    if (isset($_FILES['image4'])) $article->storeUploadedImage($_FILES['image4'], '4'); 
    if (isset($_FILES['image5'])) $article->storeUploadedImage($_FILES['image5'], '5'); 
    header("Location: admin.php?status=changesSaved"); 

Изменить article.php:

Найти этот

public function storeUploadedImage($image) { 

Изменение этого:

public function storeUploadedImage($image, $postfix) { 

найти Также это:

if (is_uploaded_file ($tempFilename)) { 
    if (!(move_uploaded_file($tempFilename, $this->getImagePath()))) trigger_error("Article::storeUploadedImage(): Couldn't move uploaded file.", E_USER_ERROR); 
    if (!(chmod($this->getImagePath(), 0666))) trigger_error("Article::storeUploadedImage(): Couldn't set permissions on uploaded file.", E_USER_ERROR); 
    } 

И изменить это:

$image_name = implode('_', explode(' ', $this->title)) . '_' . $postfix; 
    if (is_uploaded_file ($tempFilename)) { 
    if (!(move_uploaded_file($tempFilename, $this->getImagePath(IMG_TYPE_FULLSIZE, $image_name)))) trigger_error("Article::storeUploadedImage(): Couldn't move uploaded file.", E_USER_ERROR); 
    if (!(chmod($this->getImagePath(IMG_TYPE_FULLSIZE, $image_name), 0666))) trigger_error("Article::storeUploadedImage(): Couldn't set permissions on uploaded file.", E_USER_ERROR); 
    } 

И, наконец, заменить метод getImagePath (функция) с этим:

public function getImagePath($type=IMG_TYPE_FULLSIZE, $title = null) { 
    if($title !== null) 
    { 
     return ($this->imageExtension) ? (ARTICLE_IMAGE_PATH . "/$type/" . $title . $this->imageExtension) : false; 
    } 
    else 
    { 
     return ($this->id && $this->imageExtension) ? (ARTICLE_IMAGE_PATH . "/$type/" . $this->id . $this->imageExtension) : false; 
    } 
} 

Вы также должны изменить свою форму для загрузки изображения:

 <li> 
     <label for="image">New Image</label> 
     <input type="file" name="image" id="image" placeholder="Choose an image to upload" maxlength="255" /> 
     <label for="image2">New Image2</label> 
     <input type="file" name="image2" id="image2" placeholder="Choose an image to upload" maxlength="255" /> 
     ... 
     </li> 
Смежные вопросы