Gå til innhold

Opplastingsscript for flere filer


Anbefalte innlegg

Det ble postet en link til et javascript i webkafeen som lot deg laste opp flere filer på en gang. Men jeg trenger et serverside script som tar seg av overførselen.

 

Jeg har prøvd å modifisere et enkelt opplastingsscript som jeg fant på Hotscripts, men det skjer ikke noe når jeg trykker "submit/upload". Jeg har prøvd å bytte ut "userfile" med "my_file_element" i phpscriptet, men jeg har sikker byttet det ut feil en eller annen plass siden det ikke fungerer å laste opp.

 

Kan noen hjelpe meg med dette?

 

Eksempel fra opplastingsscript med flere objekter:

	<!-- Include the javascript -->
<script src="multifile_compressed.js"></script>
</head>

<body>

<!-- This is the form -->
<form enctype="multipart/form-data" action="your_script_here.script" method = "post">
<!-- The file element -- NOTE: it has an ID -->
<input id="my_file_element" type="file" name="file_1" >
<input type="submit">
</form>
Files:
<!-- This is where the output will appear -->
<div id="files_list"></div>
<script>
<!-- Create an instance of the multiSelector class, pass it the output target and the max number of files -->
var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 20 );
<!-- Pass in the file element -->
multi_selector.addElement( document.getElementById( 'my_file_element' ) );
</script>
</body>
</html>

 

Javascript

/**
* Convert a single file-input element into a 'multiple' input list
*
* Usage:
*
*   1. Create a file input element (no name)
*      eg. <input type="file" id="first_file_element">
*
*   2. Create a DIV for the output to be written to
*      eg. <div id="files_list"></div>
*
*   3. Instantiate a MultiSelector object, passing in the DIV and an (optional) maximum number of files
*      eg. var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 3 );
*
*   4. Add the first element
*      eg. multi_selector.addElement( document.getElementById( 'first_file_element' ) );
*
*   5. That's it.
*
*   You might (will) want to play around with the addListRow() method to make the output prettier.
*
*   You might also want to change the line 
*       element.name = 'file_' + this.count;
*   ...to a naming convention that makes more sense to you.
* 
* Licence:
*   Use this however/wherever you like, just don't blame me if it breaks anything.
*
* Credit:
*   If you're nice, you'll leave this bit:
*  
*   Class by Stickman -- http://www.the-stickman.com
*      with thanks to:
*      [for Safari fixes]
*         Luis Torrefranca -- http://www.law.pitt.edu
*         and
*         Shawn Parker & John Pennypacker -- http://www.fuzzycoconut.com
*      [for duplicate name bug]
*         'neal'
*/
function MultiSelector( list_target, max ){

// Where to write the list
this.list_target = list_target;
// How many elements?
this.count = 0;
// How many elements?
this.id = 0;
// Is there a maximum?
if( max ){
 this.max = max;
} else {
 this.max = -1;
};

/**
 * Add a new file input element
 */
this.addElement = function( element ){

 // Make sure it's a file input element
 if( element.tagName == 'INPUT' && element.type == 'file' ){

 	// Element name -- what number am I?
 	element.name = 'file_' + this.id++;

 	// Add reference to this object
 	element.multi_selector = this;

 	// What to do when a file is selected
 	element.onchange = function(){

   // New file input
   var new_element = document.createElement( 'input' );
   new_element.type = 'file';

   // Add new element
   this.parentNode.insertBefore( new_element, this );

   // Apply 'update' to element
   this.multi_selector.addElement( new_element );

   // Update list
   this.multi_selector.addListRow( this );

   // Hide this: we can't use display:none because Safari doesn't like it
   this.style.position = 'absolute';
   this.style.left = '-1000px';

 	};
 	// If we've reached maximum number, disable input element
 	if( this.max != -1 && this.count >= this.max ){
   element.disabled = true;
 	};

 	// File element counter
 	this.count++;
 	// Most recent element
 	this.current_element = element;
 	
 } else {
 	// This can only be applied to file input elements!
 	alert( 'Error: not a file input element' );
 };

};

/**
 * Add a new row to the list of files
 */
this.addListRow = function( element ){

 // Row div
 var new_row = document.createElement( 'div' );

 // Delete button
 var new_row_button = document.createElement( 'input' );
 new_row_button.type = 'button';
 new_row_button.value = 'Delete';

 // References
 new_row.element = element;

 // Delete function
 new_row_button.onclick= function(){

 	// Remove element from form
 	this.parentNode.element.parentNode.removeChild( this.parentNode.element );

 	// Remove this row from the list
 	this.parentNode.parentNode.removeChild( this.parentNode );

 	// Decrement counter
 	this.parentNode.element.multi_selector.count--;

 	// Re-enable input element (if it's disabled)
 	this.parentNode.element.multi_selector.current_element.disabled = false;

 	// Appease Safari
 	//    without it Safari wants to reload the browser window
 	//    which nixes your already queued uploads
 	return false;
 };

 // Set row value
 new_row.innerHTML = element.value;

 // Add button
 new_row.appendChild( new_row_button );

 // Add it to the list
 this.list_target.appendChild( new_row );
 
};

};

 

 

 

Opplastingscript fra Hotscripts

<?php
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//   You may change maxsize, and allowable upload file types.
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//Mmaximum file size. You may increase or decrease.
$MAX_SIZE = 2000000;
                           
//Allowable file Mime Types. Add more mime types if you want
$FILE_MIMES = array('image/jpeg','image/jpg','image/gif'
                  ,'image/png','application/msword');

//Allowable file ext. names. you may add more extension names.            
$FILE_EXTS  = array('.zip','.jpg','.png','.gif'); 

//Allow file delete? no, if only allow upload only
$DELETABLE  = true;                               


//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//   Do not touch the below if you are not confident.
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/************************************************************
*     Setup variables
************************************************************/
$site_name = $_SERVER['HTTP_HOST'];
$url_dir = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$url_this =  "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

$upload_dir = "files/";
$upload_url = $url_dir."/files/";
$message ="";

/************************************************************
*     Create Upload Directory
************************************************************/
if (!is_dir("files")) {
 if (!mkdir($upload_dir))
 	die ("upload_files directory doesn't exist and creation failed");
 if (!chmod($upload_dir,0755))
 	die ("change permission to 755 failed.");
}

/************************************************************
*     Process User's Request
************************************************************/
if ($_REQUEST[del] && $DELETABLE)  {
 $resource = fopen("log.txt","a");
 fwrite($resource,date("Ymd h:i:s")."DELETE - $_SERVER[REMOTE_ADDR]"."$_REQUEST[del]\n");
 fclose($resource);
 
 if (strpos($_REQUEST[del],"/.")>0);                  //possible hacking
 else if (strpos($_REQUEST[del],$upload_dir) === false); //possible hacking
 else if (substr($_REQUEST[del],0,6)==$upload_dir) {
   unlink($_REQUEST[del]);
   print "<script>window.location.href='$url_this?message=deleted successfully'</script>";
 }
}
else if ($_FILES['userfile']) {
 $resource = fopen("log.txt","a");
 fwrite($resource,date("Ymd h:i:s")."UPLOAD - $_SERVER[REMOTE_ADDR]"
           .$_FILES['userfile']['name']." "
           .$_FILES['userfile']['type']."\n");
 fclose($resource);

$file_type = $_FILES['userfile']['type']; 
 $file_name = $_FILES['userfile']['name'];
 $file_ext = strtolower(substr($file_name,strrpos($file_name,".")));

 //File Size Check
 if ( $_FILES['userfile']['size'] > $MAX_SIZE) 
    $message = "The file size is over 2MB.";
 //File Type/Extension Check
 else if (!in_array($file_type, $FILE_MIMES) 
         && !in_array($file_ext, $FILE_EXTS) )
    $message = "Sorry, $file_name($file_type) is not allowed to be uploaded.";
 else
    $message = do_upload($upload_dir, $upload_url);
 
 print "<script>window.location.href='$url_this?message=$message'</script>";
}
else if (!$_FILES['userfile']);
else 
$message = "Invalid File Specified.";

/************************************************************
*     List Files
************************************************************/
$handle=opendir($upload_dir);
$filelist = "";
while ($file = readdir($handle)) {
  if(!is_dir($file) && !is_link($file)) {
     $filelist .= "<a href='$upload_dir$file'>".$file."</a>";
     if ($DELETABLE)
       $filelist .= " <a href='?del=$upload_dir".urlencode($file)."' title='delete'>x</a>";
     $filelist .= "<sub><small><small><font color=grey>  ".date("d-m H:i", filemtime($upload_dir.$file))
                  ."</font></small></small></sub>";
     $filelist .="<br>";
  }
}

function do_upload($upload_dir, $upload_url) {

$temp_name = $_FILES['userfile']['tmp_name'];
$file_name = $_FILES['userfile']['name']; 
 $file_name = str_replace("\\","",$file_name);
 $file_name = str_replace("'","",$file_name);
$file_path = $upload_dir.$file_name;

//File Name Check
 if ( $file_name =="") { 
 	$message = "Invalid File Name Specified";
 	return $message;
 }

 $result  =  move_uploaded_file($temp_name, $file_path);
 if (!chmod($file_path,0777))
   $message = "change permission to 777 failed.";
 else
   $message = ($result)?"$file_name uploaded successfully." :
           "Somthing is wrong with uploading a file.";
 return $message;
}

?>

Endret av Garreth
Lenke til kommentar
Videoannonse
Annonse

Merkelig, for jeg klarer å laste opp når jeg ikke har javascriptet på. Når jeg har det på, så klarer jeg å hente inn filer, men når jeg trykker upload så skjer det ingenting (siden bare refresher seg)

 

med print_r($_FILES); får jeg

Array ( [file_0] => Array ( [name] => AA050372.jpg [type] => image/jpeg [tmp_name] => /var/tmp/phprDKtdS [error] => 0 [size] => 29779 ) [file_1] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) ) 

 

Jeg skjønner desverre ikke så mye av det :roll:

 

Edit: Jeg hadde visst glemt å ta med skjemaet som er i upload scriptet

 

   <font color=red><?=$_REQUEST[message]?></font>
  <br>
  <form name="upload" id="upload" ENCTYPE="multipart/form-data" method="post">
    Upload File <input type="file" id="userfile" name="userfile">
    <input type="submit" name="upload" value="Upload">
  </form>

  <br><b>My Files</b>
  <hr width=70%>
  <?=$filelist?>
  <hr width=70%>

 

Jeg tror feilen skjer fordi at både "name" og "id" har samme navn, men hvis jeg bytter ut "name" med noe annet både i skjemaet og i php koden så laster den ikke opp lenger. Så hvis noen ser hva som er galt her så hadde det vært veldig fint!

Endret av Garreth
Lenke til kommentar

Nå får jeg til å laste opp mens jeg har på javascriptet. Det lister opp som normalt, men når jeg trykker "upload" så kommer bare den første filen med.

 

Edit: Jeg får heller ikke noe error fra print_r($_FILES); heller når jeg laster opp.

 

Edit 2:

Jeg fant et annet script som ikke brukte javascript. Bruker heller det.

 

Dette er koden jeg bruker nå:

<?php
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//   You may change maxsize, and allowable upload file types.
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//Mmaximum file size. You may increase or decrease.
$MAX_SIZE = 20000000;
                           
//Allowable file Mime Types. Add more mime types if you want
$FILE_MIMES = array('image/jpeg','image/jpg','image/gif'
                  ,'image/png','application/msword');

//Allowable file ext. names. you may add more extension names.            
$FILE_EXTS  = array('.zip','.jpg','.png','.gif','.pdf','.rar'); 

//Allow file delete? no, if only allow upload only
$DELETABLE  = true;                               


//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//   Do not touch the below if you are not confident.
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/************************************************************
*     Setup variables
************************************************************/
$site_name = $_SERVER['HTTP_HOST'];
$url_dir = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$url_this =  "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

$upload_dir = "files/";
$upload_url = $url_dir."/files/";
$message ="";

/************************************************************
*     Create Upload Directory
************************************************************/
if (!is_dir("files")) {
 if (!mkdir($upload_dir))
 	die ("upload_files directory doesn't exist and creation failed");
 if (!chmod($upload_dir,0755))
 	die ("change permission to 755 failed.");
}

/************************************************************
*     Process User's Request
************************************************************/
if ($_REQUEST[del] && $DELETABLE)  {
 $resource = fopen("log.txt","a");
 fwrite($resource,date("Ymd h:i:s")."DELETE - $_SERVER[REMOTE_ADDR]"."$_REQUEST[del]\n");
 fclose($resource);
 
 if (strpos($_REQUEST[del],"/.")>0);                  //possible hacking
 else if (strpos($_REQUEST[del],$upload_dir) === false); //possible hacking
 else if (substr($_REQUEST[del],0,6)==$upload_dir) {
   unlink($_REQUEST[del]);
   print "<script>window.location.href='$url_this?message=deleted successfully'</script>";
 }
}
else if ($_FILES['file_1']) {
 $resource = fopen("log.txt","a");
 fwrite($resource,date("Ymd h:i:s")."UPLOAD - $_SERVER[REMOTE_ADDR]"
           .$_FILES['file_1']['name']." "
           .$_FILES['file_1']['type']."\n");
 fclose($resource);

$file_type = $_FILES['file_1']['type']; 
 $file_name = $_FILES['file_1']['name'];
 $file_ext = strtolower(substr($file_name,strrpos($file_name,".")));

 //File Size Check
 if ( $_FILES['userfile']['size'] > $MAX_SIZE) 
    $message = "The file size is over 2MB.";
 //File Type/Extension Check
 else if (!in_array($file_type, $FILE_MIMES) 
         && !in_array($file_ext, $FILE_EXTS) )
    $message = "Sorry, $file_name($file_type) is not allowed to be uploaded.";
 else
    $message = do_upload($upload_dir, $upload_url);
 
 print "<script>window.location.href='$url_this?message=$message'</script>";
}
else if (!$_FILES['file_1']);
else 
$message = "Invalid File Specified.";

/************************************************************
*     List Files
************************************************************/
$handle=opendir($upload_dir);
$filelist = "";
while ($file = readdir($handle)) {
  if(!is_dir($file) && !is_link($file)) {
     $filelist .= "<a href='$upload_dir$file'>".$file."</a>";
     if ($DELETABLE)
       $filelist .= " <a href='?del=$upload_dir".urlencode($file)."' title='slett denne filen'>slett</a>";
     $filelist .= "<sub><small><small><font color=grey>  ".date("d-m H:i", filemtime($upload_dir.$file))
                  ."</font></small></small></sub>";
     $filelist .="<br>";
  }
}

function do_upload($upload_dir, $upload_url) {

$temp_name = $_FILES['file_1']['tmp_name'];
$file_name = $_FILES['file_1']['name']; 
 $file_name = str_replace("\\","",$file_name);
 $file_name = str_replace("'","",$file_name);
$file_path = $upload_dir.$file_name;

//File Name Check
 if ( $file_name =="") { 
 	$message = "Invalid File Name Specified";
 	return $message;
 }

 $result  =  move_uploaded_file($temp_name, $file_path);
 if (!chmod($file_path,0777))
   $message = "change permission to 777 failed.";
 else
   $message = ($result)?"$file_name uploaded successfully." :
           "Somthing is wrong with uploading a file.";
 return $message;
}



print_r($_FILES);
?>
<html>

<head>
<!-- Include the javascript -->
<script src="multifile.js"></script>
<title>Upload</title>
</head>

<body>

<center>
  <strong><?=$_REQUEST[message]?></strong>
  <br>
  <form name="upload" id="upload" ENCTYPE="multipart/form-data" method="post">
    Upload File <input id="my_file_element" type="file" name="file_1" >
    <input type="submit" name="upload" value="Upload">
  </form>
Files:
<!-- This is where the output will appear -->
<div id="files_list"></div>
<script>
<!-- Create an instance of the multiSelector class, pass it the output target and the max number of files -->
var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 20 );
<!-- Pass in the file element -->
multi_selector.addElement( document.getElementById( 'my_file_element' ) );
</script>


  <br><b>My Files</b>
  <hr width=70%>
  <?=$filelist?>
  <hr width=70%>
</center>

</body>
</html>

Endret av Garreth
Lenke til kommentar

Opprett en konto eller logg inn for å kommentere

Du må være et medlem for å kunne skrive en kommentar

Opprett konto

Det er enkelt å melde seg inn for å starte en ny konto!

Start en konto

Logg inn

Har du allerede en konto? Logg inn her.

Logg inn nå
×
×
  • Opprett ny...