2017-05-27 73 views
1

我的表格中有一個'Upload-File'字段,供我的網站訪問者上傳圖片。我可以使用表單字段重命名上傳圖像文件嗎?

<input type="file" name="fileToUpload" id="fileToUpload"> 

目前,該文件被保存到我的服務器與它上傳相同的'名稱'。

我想爲我的表單添加一個輸入字段(如下所示),以便用戶可以爲[圖像]文件輸入一個新的「名稱」。

<input name="imageRename" id="imageRename"> 

我需要一些建議,改變當前的PHP代碼重命名文件,然後保存到我的服務器。

這裏是圖像處理當前的PHP代碼:

文件上傳調用image_10.jpg

文件名,你whant imag_xpto.jpg:

<?php 
$target_dir = "articles/article-images/"; 
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
if(isset($_POST["submit"])) 
{ 
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
    if($check !== false) 
    { 
     echo "". $check[""].""; $uploadOk = 1; 
    } 
    else 
    { 
     echo "&#xd7; FILE IS NOT AN IMAGE"; $uploadOk = 0; 
    } 
} 
if(file_exists($target_file)) 
{ 
    echo "&#xd7; THIS IMAGE ALREADY EXIST ON SERVER"; $uploadOk = 0; 
} 
if ($_FILES["fileToUpload"]["size"] > 500000) 
{ 
    echo "&#xd7; FILE IS TOO LARGE"; $uploadOk = 0; 
} 
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") 
{ 
    echo "&#xd7; ONLY JPG, JPEG, PNG & GIF FILES ARE PERMITTED"; $uploadOk = 0; 
} 
if ($uploadOk == 0) 
{ 
    echo "&#xd7; IMAGE WAS NOT UPLOADED"; 
} 
else 
{ 
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) 
    { 
     echo '<img class="fixed-ratio-resize" src="../../articles/article-images/'. basename($_FILES["fileToUpload"]["name"]). '">'; 
    } 
    else 
    { 
     echo "&#xd7; IMAGE WAS NOT UPLOADED"; 
    } 
} 
    ?> 
+0

如果要重命名文件,請使用'move_uploaded_file'。您的目標文件名'$ target'將是您想要保存文件的新名稱和路徑。 –

回答

0

用於我的評論例如

要更改的代碼:

$target_dir = "articles/article-images/"; 
$target_new_name = "imag_xpto.jpg"; 
//your code... 
$target = $target_dir.$target_new_name; 
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){ 
//Your code... 

如果你想要一個字段給出新的名字,你只需要在你的html中創建一個輸入字段並使用這個代碼來獲取它。對於後

代碼:

HTML:

<input type = "text" name = "inputfieldname"> 

PHP:

$target_new_name = $_POST['inputfieldname']; 

你一些提示調試和改進代碼

<?php 

if(isset($_POST["submit"])) 
{ 
    $target_new_name = $_POST["inputfieldname"]; //you can and you should protect, if you are sending null or empty or undefined it can cause problems in the future. For protect you can use isset and verify if the name it's null or "". 
$target_dir = "articles/article-images/"; 
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
$target_new_file_name = $target_dir.$target_new_name.".".$imageFileType; // Check with an "error_log($target_new_file_name);" the string "$target_new_file_name". Because it is in the creation of the new string, that the problems occur 
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
    if($check !== false) 
    { 
     echo "". $check[""].""; $uploadOk = 1; 
    } 
    else 
    { 
     echo "&#xd7; FILE IS NOT AN IMAGE"; $uploadOk = 0; 
    } 
} 
//if(file_exists($target_file)) - You should now verify that the new file name exists on the server 

if(file_exists($target_new_file_name)) 
{ 
    echo "&#xd7; THIS IMAGE ALREADY EXIST ON SERVER"; $uploadOk = 0; 
} 
if ($_FILES["fileToUpload"]["size"] > 500000) 
{ 
    echo "&#xd7; FILE IS TOO LARGE"; $uploadOk = 0; 
} 
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") 
{ 
    echo "&#xd7; ONLY JPG, JPEG, PNG & GIF FILES ARE PERMITTED"; $uploadOk = 0; 
} 
if ($uploadOk == 0) 
{ 
    echo "&#xd7; IMAGE WAS NOT UPLOADED"; 
} 
else 
{ 
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_new_file_name)) 
    { 
     echo '<img class="fixed-ratio-resize" src="'.$target_new_file_name.'">'; // I'm not really sure about this part of the code, I'm used to another type of html creation in php 
    } 
    else 
    { 
     echo "&#xd7; IMAGE WAS NOT UPLOADED"; 
    } 
} 
    ?> 

我有代碼沒有機會測試以便代碼中可能存在一些錯誤。

簡單的方法。任何問題,只是要求我會嘗試回答

+0

謝謝你的時間和建議何塞。我試過你的代碼。到目前爲止沒有運氣。我想也許我仍然對你的編輯/添加應該去哪裏感到困惑。注意:我在這裏發佈的代碼中的代碼按照我需要的方式工作,除了名稱更改。其餘的工作很好。我只是希望圖像文件在表單的輸入字段中保存一個新名稱。您是否可以在我的完整代碼中包含您的編輯來實現這一點?注意:另外...爲了節省一些麻煩...將提供新文件名的表單文本字段命名爲'timeValue'。 –

+0

如果你想這樣做,你需要把你的HTML從你的表單中。 –

+0

這裏是一個精簡版的表格:

<輸入類= 「提交按鈕」 類型= 「提交」 名稱= 「提交」 值= 「SUBMIT」>

0

您應該測試用戶實際提交了新名稱的值,如果不使用原始(或隨機)。另外 - 您可以使用$ _FILES對象中預定義的錯誤特性來幫助處理。

<?php 

    $filefield='fileToUpload'; 
    $textfield='imageRename'; 

    /* 
     function to return the reason for any failure 
    */ 
    function uploaderror($code){ 
     switch($code) { 
      case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
      case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
      case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded"; 
      case UPLOAD_ERR_NO_FILE: return "No file was uploaded"; 
      case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder"; 
      case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk"; 
      case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension"; 
      default: return "Unknown upload error"; 
     } 
    } 

    /* 
     test that the required items are present in posted data 
    */ 
    if(isset($_FILES[ $filefield ],$_POST[ $textfield ])){ 

     $target_dir = "articles/article-images/"; 
     $errors=array(); 

     /* set permitted file extensions - not foolproof btw */ 
     $allowed=array('jpg','jpeg','png','gif'); 

     /* get the properties of the uploaded file */ 
     $obj=(object)$_FILES[ $filefield ]; 
     $name=$obj->name; 
     $tmp=$obj->tmp_name; 
     $size=$obj->size; 
     $error=$obj->error; 
     $type=$obj->type; 


     /* 
      determine the new name of the file if the user supplied a new name or not 
     */ 
     $newname = !empty($_POST[ $textfield ]) ? $_POST[ $textfield ] : false; 
     $ext = pathinfo($name, PATHINFO_EXTENSION); 

     $name =($newname) ? $newname .= ".{$ext}" : $name; 


     /* no errors so far, proceed with logical tests of your own */ 
     if($error==UPLOAD_ERR_OK){ 

      if(!in_array($ext,$allowed)) $errors[]="&#xd7; ONLY JPG, JPEG, PNG & GIF FILES ARE PERMITTED"; 
      if($size > 500000)$errors[]="&#xd7; FILE IS TOO LARGE"; 
      if(!getimagesize($tmp))$errors[]="&#xd7; FILE IS NOT AN IMAGE"; 
      if(!is_uploaded_file($tmp))$errors[]="&#xd7; POSSIBLE FILE UPLOAD ATTACK"; 


      if(empty($errors)){ 
       /* 
        set the new file location 
       */ 
       $targetfile = $target_dir . DIRECTORY_SEPARATOR . $name; 

       /* 
        save the file 
       */ 
       $status = move_uploaded_file($tmp, $targetfile); 

       /* 
        determine what to do if it succeeded or not 
       */ 
       if($status){ 
        echo '<img class="fixed-ratio-resize" src="../../articles/article-images/'. basename($name). '" />'; 
       } else { 
        exit('error'); 
       } 
      } else {/* edited: changed commas to periods */ 
       exit('<pre>'.print_r($errors,1).'</pre>'); 
      } 
     } else { 
      exit(uploaderror($error)); 
     } 
    } 
?> 

以上工作得很好,當我測試了這個使用下面的表格 - 唯一的另一個區別是,我已經設置爲c:\temp\fileuploads用於測試目的的目標目錄路徑。

<form id='fileupload' action='/test/so_upload_image_target.php' method='post' enctype='multipart/form-data'> 
     <h1>Upload an image - test</h1> 
     <input type='file' name='fileToUpload' /> 
     <input type='text' name='imageRename' value='boobies' /> 
     <input type='submit' /> 
    </form> 
+0

謝謝拉姆。關於測試你的代碼。我假設你在$ textfield的位置,我將用提供該名稱的文本字段的名稱替換它,是的?另外...我得到一個語法錯誤的線:退出('

',print_r($errors,1),'
');但是我會嘗試代碼。我會在反饋後馬上回來。 –

+0

不幸的是,該代碼無效。它不僅沒有保存圖像....它也導致我的html不顯示。該html文件沒有保存到正確的文件夾,但沒有顯示。圖像沒有保存或顯示。 –

+0

在PHP錯誤日誌中是否存在錯誤? – RamRaider

相關問題