Upload image to the server and rename it

3

Good day, basically I need to take a picture and re-name it with the name that the user provides in an input and upload it to the server.

With this code, the images are already uploaded to the server, it would only be necessary to name them with the key provided by the user in the input, because if I try to do it in the manner below it marks me the following error:

Notice: Undefined index: clave in C:\wamp64\www\Idis\php\upload.php on line 2

HTML Code:

<form id="formUpl">
  <input id="fachada" name="clave"/>
  <span>Imagenes</span>
  <input type="file" name="archivo[]" multiple>
  <button type="submit">Subir</button>
</form>

JS Code

$("#formUpl").submit(function(e) {
        e.preventDefault();
        var formulario = new FormData($(this)[0]);
        $.ajax({
            method: "post",
            url: "php/upload.php",
            data:formulario,
            cache: false,
            processData: false,
            contentType: false,
            success: function(respAX) {
                if (respAX == 0) {
                    alert("ERROR");
                } else {
                    console.log(respAX);
                }
            }
        });
    });

And the Php code with which I want to name the photo and upload it to the server.

<?php
$clave = $_POST['clave'];
$total = count($_FILES['archivo']['name']);
for($i=0; $i<$total; $i++) {
  $tmpFilePath = $_FILES['archivo']['tmp_name'][$i];
  if ($tmpFilePath != ""){
    $newname = $clave.'.jpg';
    print_r($clave); 
    if(move_uploaded_file($tmpFilePath,"uploads/".$newname)) {
        echo 1;
    }else{
        echo 0;
    }
  }
}
?>
    
asked by Cristhian Rivera 22.01.2018 в 19:32
source

1 answer

1

In your php code you should add the following;

move_uploaded_file($_FILES['archivo']['tmp_name'], $carpeta_destino . $nombre_archivo);

Eye, based on my experience create this function to extract the file extension and save it with the name you choose (or in your case the user places);

//Este codigo va antes que todo

function extencion_archivo($nombre_archivo){
            $path = $nombre_archivo;
            $ext = pathinfo($path, PATHINFO_EXTENSION);
            return $ext;
        }

It would stay like this;

<?php

$clave = $_POST['clave'];
$nombre_archivo=$clave.".".extencion_archivo($_FILES['archivo']['name']) ;
$total = count($_FILES['archivo']['name']);
for($i=0; $i<$total; $i++) {
  $tmpFilePath = $_FILES['archivo']['tmp_name'][$i];
  if ($tmpFilePath != ""){
     move_uploaded_file($_FILES['archivo']['tmp_name'], $carpeta_destino . $nombre_archivo);
    print_r($clave); 
    if(move_uploaded_file($tmpFilePath,"uploads/".$nombre_archivo)) {
        echo 1;
    }else{
        echo 0;
    }
  }
}
?>
    
answered by 22.01.2018 в 19:46