Questo codice e’ il frutto delle pillole di marketto e xpilux .
Le due permettevano uno di fare upload multiplo e l’altro upload singolo piu’ resize delle immagini creando anche le thumb.
Prima di continuare, si consiglia l’attenta lettura delle suddette pillole.
Ho preso le due e ho fatto il merge…
Il codice risultante sara’ il seguente:
config.php
Codice PHP:
<?PHP
define('TMP_DIR', './tmp');
define('IMAGE_DIR', './img_big');
define('THUMB_DIR', './img_small');
define('IMAGE_QUALITY', 80);
define('THUMB_QUALITY', 70);
define('IMAGE_HEIGHT', 400);
define('THUMB_HEIGHT', 75);
?>
index.htm
Codice PHP:
<html>
<head>
<script type="text/javascript" src="include/esterno.js"></script>
</head>
<body>
<form action="upload.php" method="POST" name="modulo" enctype="multipart/form-data">
<table border="1">
<tr>
<td>Upload file multipli</td>
</tr>
<tr>
<td>
<div id="attachment" style="display:none">
<input id="file" name="file" type="file" size="55" />
[url="#"] Rimuovi[/url]
</div>
</td>
</tr>
<tr>
<td>
<div id="attachments">
<input name="file[]" type="file" size="55" />
<span id="attachmentmarker"></span>
</div>
</td>
</tr>
<tr>
<td>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
[url="javascript:addUpload('file')"]Aggiungi file[/url]
<div align="right"><input name="submit_upload" type="submit" value="Invia" /></div>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</form>
</body>
</html>
upload.php
Codice PHP:
<?PHP
if(!isset($_POST['submit_upload']))
header("Location: index.php");
else{
include_once 'config.php';
//faccio l'upload dell'img
include_once './include/upload.class.php';
if(!isset($_FILES)) $_FILES = $HTTP_POST_FILES;
if(!isset($_SERVER)) $_FILES = $HTTP_POST_VARS;
if (count($_FILES) > 0){
$numero_file= count($_FILES['file']['tmp_name']);
for($i=0;$i<$numero_file;$i++)
if(empty($_FILES['file']['size'][$i])){
echo "L'UPLOAD DEL FILE [b]{$_FILES['file']['name'][$i]}[/b] NON E' ANDATO A BUON FINE!
\n";
unset( $_FILES['file']['name'][$i]);
unset( $_FILES['file']['type'][$i]);
unset( $_FILES['file']['size'][$i]);
unset( $_FILES['file']['error'][$i]);
unset( $_FILES['file']['tmp_name'][$i]);
}
// riconteggio il numero dei file che sto caricando in quanto prima ho eliminato quelli vuoti
$numero_file = count( $_FILES['file']['tmp_name']);
foreach($_FILES['file']['name'] as $chiave=>$valore){
$up = new FileUpload(TMP_DIR);
$up->Upload($_FILES['file']['name'][$chiave],$_FILES['file']['tmp_name'][$chiave]);
//adesso ridimensiono l'img a 400 x 400
include_once './include/image.class.php';
$img = new Image(TMP_DIR . '/' . $up->filename);
//creo l'immagine sorgente
$result = $img->CreateSourceImage();
//se il tipo di immagine è supportato salvo 2 file:
//uno con l'img grande e uno con l'img piccola nelle rispettive directory
if($result){
//salvo l'immagine con altezza 400 lasciandola proporzionata
$img->SaveProportionateImage(IMAGE_DIR . '/' . $up->filename, IMAGE_QUALITY, IMAGE_HEIGHT);
//salvo l'immagine con altezza 75 lasciandola proporzionata
$img->SaveProportionateImage(THUMB_DIR . '/' . $up->filename, THUMB_QUALITY, THUMB_HEIGHT);
//libero la memoria cancellando l'immagine sorgente
$img->Free();
}
//se il tipo di img non è supportata
//o se il file uploadato nn è un immagine
else
echo 'Immagine non valida
';
//In ogni caso cancello il file uploadato nella cartella ./tmp
$up->DeleteFile();
}
echo '[url="view.php"]Guarde le immagini[/url]';
}
}
?>
view.php
Codice PHP:
<?
include'config.php';
$dir=dir(THUMB_DIR);
while($img = $dir->read())
if(($img != '.') & ($img != '..'))
echo'[url="'.IMAGE_DIR.'/'.$img.'"][img]'.THUMB_DIR.'/'.$img.'[/img][/url]';
?>
include/esterno.js
codice:
// JavaScript Document
var max = 0; // maximum # of attachments allowed
var currentUploads = 0; // current # of attachment sections on the web page
var nameDesc = ''; // Name property for the Description Input field
var nameFile = ''; // Name property for the File Input field
var scrollPosVert = 0; // stores the current scroll position on the form
// for some reason when a div is taken out, the form
// will scroll to the top on both Firefox and IE
// SCROLL FUNCTIONS
function saveScrollPos(offset){
scrollPosVert=(document.all)?document.body.scrollTop:window.pageYOffset-offset;
}
function setScrollPos(){
window.scrollTo(0, scrollPosVert);
setTimeout('window.scrollTo(0, scrollPosVert)',1);
}
// This function adds a new attachment section to the form
// It is called when the user clicks the "Attach a file" button...
// It takes three arguments:
// maxUploads - the maximum number of attachments allowed
// descFieldName - the field name for the Description Input field
// fileFieldName - the field name for the File Input field
function addUpload(fileFieldName){
nameFile=fileFieldName;
currentUploads++;
if (currentUploads>0)
document.getElementById('addupload').childNodes[0].data='Aggiungi file';
// First, clone the hidden attachment section
var newFields = document.getElementById('attachment').cloneNode(true);
newFields.id = '';
// Make the new attachments section visible
newFields.style.display = 'block';
// loop through tags in the new Attachment section
// and set ID and NAME properties
//
// NOTE: the control names for the Description Input
// field and the file input field are created
// by appending the currentUploads variable
// value to the nameFile and nameDesc values
// respectively
//
// In terms of Xaraya, this means you'll need to name your
// DD properties will need names like the following:
// "AttachmentDesc1"
// "AttachmentFile1"
// "AttachmentDesc2"
// "AttachmentFile2"
// "AttachmentDesc3"
// "AttachmentFile3"
// et cetera...
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++){
if (newField[i].name==nameFile){
newField[i].id=nameFile+currentUploads;
newField[i].name=nameFile+'[]';
}
}
// Insert our new Attachment section into the Attachments Div
// on the form...
var insertHere = document.getElementById('attachmentmarker');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
// This function removes an attachment from the form
// and updates the ID and Name properties of all other
// Attachment sections
function removeFile(container, item){
// get the ID number of the upload section to remove
var tmp = item.getElementsByTagName('input')[0];
var basefieldname = '';
basefieldname = nameFile;
var iRemove=Number(tmp.id.substring(basefieldname.length, tmp.id.length));
// Shift all INPUT field IDs and NAMEs down by one (for fields with a
// higher ID than the one being removed)
var x = document.getElementById('attachments').getElementsByTagName('input');
for (i=0;i<x.length;i++){
basefieldname=nameFile;
var iEdit = Number(x[i].id.substring(basefieldname.length, x[i].id.length));
if (iEdit>iRemove){
x[i].id=basefieldname+(iEdit-1);
x[i].name=basefieldname+(iEdit-1);
}
}
// Run through all the DropCap divs (the number to the right of the attachment
// section) and update that number...
x=document.getElementById('attachments').getElementsByTagName('div');
for (i=0;i<x.length;i++){
// Verify this is actually the "dropcap" div
if (x[i].id.substring(0, String('dropcap').length)=='dropcap'){
ID = Number(x[i].id.substring(String('dropcap').length, x[i].id.length));
// check to see if current attachment had a higher ID than the one we're
// removing (and thus needs to have its ID dropped)
if (ID>iRemove){
x[i].id='dropcap'+(ID-1);
x[i].childNodes[0].data=(ID-1);
}
}
}
currentUploads--;
saveScrollPos(0);
container.removeChild(item);
setScrollPos();
document.getElementById('addupload').style.visibility='visible';
if (currentUploads==0)
document.getElementById('addupload').childNodes[0].data='Aggiungi file';
}
include/image.class.php
Codice PHP:
<?PHP
class Image{
var $src_filename;
var $src_witdh;
var $src_height;
var $src_type;
var $src_attr;
var $src_image;
function Image($filename){
$this->src_filename = $filename;
$this->GetImageInfo();
}
function GetImageInfo(){
list($this->src_width,$this->src_height, $this->src_type, $this->src_attr) = getimagesize($this->src_filename);
}
function CreateSourceImage(){
switch($this->src_type){
case 1:
$this->src_image =imagecreatefromgif($this->src_filename);
break;
case 2:
$this->src_image =imagecreatefromjpeg($this->src_filename);
break;
case 3:
$this->src_image =imagecreatefrompng($this->src_filename);
break;
default: return false;
}
return true;
}
function SaveProportionateImage($filename, $quality, $height){
$dest_height = $height;
$ratio = $this->src_height / $dest_height;
$dest_image = imagecreatetruecolor( $this->src_width / $ratio,$dest_height);
imagecopyresampled($dest_image, $this->src_image, 0, 0, 0, 0,
$this->src_width / $ratio,
$this->src_height / $ratio,
$this->src_width,
$this->src_height);
imagejpeg($dest_image, $filename.'.jpg', $quality);
imagedestroy($dest_image);
}
function Free(){
imagedestroy($this->src_image);
}
}
?>
include/upload.class.php
Codice PHP:
<?
class FileUpload{
var $up_dir; //la directory temporanea in cui verrà uploadata l'img
var $filename; //il nome del file
function FileUpload($up_dir){
$this->up_dir = $up_dir;
}
function Upload($files_name,$files_tmp){
if(!file_exists($this->up_dir))
die('La directory non esiste!');
if(trim($files_name) == "")
die("Non hai indicato il file da uploadare!");
if(is_uploaded_file($files_tmp)){
move_uploaded_file($files_tmp,$this->up_dir."/".$this->filename)
or die("Impossibile spostare il file;controlla l'esistenza o i permessi della directory!");
}
else
die ("Problemi nell'upload del file ".$files_name);
}
function DeleteFile(){
unlink($this->up_dir . '/' . $this->filename);
}
}
?>
poi ci sono le directory vuote
img_big
img_small
…
Il tutto e’ molto molto simile al codice scritto da xPilux.
Ho riscontrato due problematiche risolvibili tranquillamente dagli esperti di javascript… (io non sono fra questi
)
1) La possibilita’ di non aggiungere file vuoti.
2) Il controllo di non aggiungere file gia’ aggiunti in precedenza.
3) Esiste la possibilita' di uploadare in una parte di sito dove non si hanno i permessi di scrittura (cambiando precedentemente i permessi alla directory naturalmente)?
Ciao