2010-08-18 19 views
37

Sto usando questo codice per caricare i file (immagini in una cartella)Come caricare e salvare i file con il nome desiderato

<form action='' method='POST' enctype='multipart/form-data'> 
<input type='file' name='userFile'><br> 
<input type='submit' name='upload_btn' value='upload'> 
</form> 

<?php 
$target_Path = "images/"; 
$target_Path = $target_Path.basename($_FILES['userFile']['name']); 
move_uploaded_file($_FILES['userFile']['tmp_name'], $target_Path); 
?> 

quando il file (immagine) viene salvato nel percorso specificato ... What If voglio salvare il file con un nome desiderato ....

ho provato a sostituire QUESTO

$target_Path = $target_Path.basename($_FILES['userFile']['name']); 

cON QUESTO

$target_Path = $target_Path.basename("myFile.png"); 

ma non sta lavorando

+0

Che cosa è esattamente "non funziona"? Qualche messaggio di errore? – deceze

+3

Non è necessario il 'basename' se si sta usando' "myFile.png" '. Non dovrebbe fare la differenza, però. – qmega

risposta

80

Si può provare questo,

$info = pathinfo($_FILES['userFile']['name']); 
$ext = $info['extension']; // get the extension of the file 
$newname = "newname.".$ext; 

$target = 'images/'.$newname; 
move_uploaded_file($_FILES['userFile']['tmp_name'], $target); 
+0

molto buono @Manie –

7

Questo funzionerebbe molto bene - Puoi utilizzare HTML5 per consentire il caricamento solo dei file di immagine. Questo è il codice per uploader.htm -

<html>  
    <head> 
     <script> 
      function validateForm(){ 
       var image = document.getElementById("image").value; 
       var name = document.getElementById("name").value; 
       if (image =='') 
       { 
        return false; 
       } 
       if(name =='') 
       { 
        return false; 
       } 
       else 
       { 
        return true; 
       } 
       return false; 
      } 
     </script> 
    </head> 

    <body> 
     <form method="post" action="upload.php" enctype="multipart/form-data"> 
      <input type="text" name="ext" size="30"/> 
      <input type="text" name="name" id="name" size="30"/> 
      <input type="file" accept="image/*" name="image" id="image" /> 
      <input type="submit" value='Save' onclick="return validateForm()"/> 
     </form> 
    </body> 
</html> 

Ora il codice per upload.php -

<?php 
$name = $_POST['name']; 
$ext = $_POST['ext']; 
if (isset($_FILES['image']['name'])) 
{ 
    $saveto = "$name.$ext"; 
    move_uploaded_file($_FILES['image']['tmp_name'], $saveto); 
    $typeok = TRUE; 
    switch($_FILES['image']['type']) 
    { 
     case "image/gif": $src = imagecreatefromgif($saveto); break; 
     case "image/jpeg": // Both regular and progressive jpegs 
     case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break; 
     case "image/png": $src = imagecreatefrompng($saveto); break; 
     default: $typeok = FALSE; break; 
    } 
    if ($typeok) 
    { 
     list($w, $h) = getimagesize($saveto); 
     $max = 100; 
     $tw = $w; 
     $th = $h; 
     if ($w > $h && $max < $w) 
     { 
      $th = $max/$w * $h; 
      $tw = $max; 
     } 
     elseif ($h > $w && $max < $h) 
     { 
      $tw = $max/$h * $w; 
      $th = $max; 
     } 
     elseif ($max < $w) 
     { 
      $tw = $th = $max; 
     } 

     $tmp = imagecreatetruecolor($tw, $th);  
     imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h); 
     imageconvolution($tmp, array(// Sharpen image 
      array(−1, −1, −1), 
      array(−1, 16, −1), 
      array(−1, −1, −1)  
     ), 8, 0); 
     imagejpeg($tmp, $saveto); 
     imagedestroy($tmp); 
     imagedestroy($src); 
    } 
} 
?> 
0

uso questo per percorso di destinazione per il caricamento

<?php 
$file_name = $_FILES["csvFile"]["name"]; 
$target_path = $dir = plugin_dir_path(__FILE__)."\\upload\\". $file_name; 
echo $target_path; 
move_uploaded_file($_FILES["csvFile"]["tmp_name"],$target_path. $file_name); 
?> 
-1

ECCO IL CODICE IN PHP PER CARICARE L'IMMAGINE NEL DATABASE, VISUALIZZARE E SALVARLO ANCHE ALLA CARTELLA LOCALE

  1. A PRIMA codice HTML per la forma:

    <div class="upload"> 
        <form method="POST" enctype="multipart/form-data" id="imageform"> 
         <br> 
         <input type="file" name="image" id="photoimg" > 
         <br><br> 
         <input type="submit" name="submit" value="UPLOAD"> 
        </form> 
    </div> 
    
  2. Ecco l'intero codice PHP:.

creare database e la tabella come si desidera (necessario solo 2 campi) Nella tabella , id(INT) 255 primary key AUTO INCREMENT and your image row(anyname) (MEDIUMBLOB)

<?php 

if(isset($_POST['submit'])){ 
    if(@getimagesize($_FILES['image']['tmp_name']) == FALSE){ 
     echo "<span class='image_select'>please select an image</span>"; 

    } 
    else{ 
     $image = addslashes($_FILES['image']['tmp_name']); 
     $name = addslashes($_FILES['image']['name']); 
     $image = file_get_contents($image); 
     $image = base64_encode($image); 
     saveimage($name,$image); 
     $uploaddir = 'profile/'; //this is your local directory 
     $uploadfile = $uploaddir . basename($_FILES['image']['name']); 

     echo "<p>"; 

      if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {// file uploaded and moved} 
      else { //uploaded but not moved} 

     echo "</p>"; 



    } 

} 

displayimage(); 
function saveimage($name,$image) 
{ 
    $con = mysql_connect("localhost","root","your database password"); 
    mysql_select_db("your database",$con); 
    $qry = "UPDATE your_table SET your_row_name='$image'"; 
     $result = @mysql_query($qry,$con); 

    if($result) 
    { 
     echo "<span class='uploaded'>IMAGE UPLOADED</span>"; 

    } 
    else 
    { 
     echo "<span class='upload_failed'>IMAGE NOT UPLOADED</span>"; 

    } 
} 
function displayimage() 
{ 
    $con = mysql_connect("localhost","root","your_password"); 
    mysql_select_db("your_database",$con); 
    $qry = "select * from your_table"; 
    $result = mysql_query($qry,$con); 

    while($row = mysql_fetch_array($result)) 
    { 
     echo '<img class="image" src="data:image;base64,'.$row[1].'">'; 

    } 



    mysql_close($con); 
} 
?> 
0

configurare il "php.ini" file

Innanzitutto, assicurarsi che PHP sia configurato per consentire il caricamento di file. Nel tuo "php.file ini", ricerca per la direttiva file_uploads, e impostarlo su On:

file_uploads = On 

creare il modulo HTML

Successivamente, creare un modulo HTML che consentono agli utenti di scegliere il file immagine che desidera caricare:

<!DOCTYPE html> 
<html> 
<body> 

<form action="upload.php" method="post" enctype="multipart/form-data"> 
    Select image to upload: 
    <input type="file" name="fileToUpload" id="fileToUpload"> 
    <input type="submit" value="Upload Image" name="submit"> 
</form> 

</body> 
</html> 

alcune regole da seguire per il modulo HTML di cui sopra: assicurarsi che il modulo utilizza method = "post" Il modulo ha anche bisogno del seguente attributo: enctype = "multipart/form-data". Specifica quale tipo di contenuto utilizzare quando si invia il modulo Senza i requisiti sopra indicati, il caricamento del file non funzionerà. Altre cose da notare: L'attributo type = "file" del tag mostra il campo di input come un controllo di selezione file, con un pulsante "Sfoglia" accanto al controllo di input Il modulo sopra invia i dati a un file chiamato " upload.php ", che creeremo in seguito.

Crea il caricamento del file di script PHP

Il file "upload.php" contiene il codice per il caricamento di un file:

<?php 
$target_dir = "uploads/"; 
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
// Check if image file is a actual image or fake image 
if(isset($_POST["submit"])) { 
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
    if($check !== false) { 
     echo "File is an image - " . $check["mime"] . "."; 
     $uploadOk = 1; 
    } else { 
     echo "File is not an image."; 
     $uploadOk = 0; 
    } 
} 
?> 
Problemi correlati