Search file name sent by json

Asked

Viewed 327 times

7

I’m using a tool to perform Crop of an image sent by the user. When Crop is done, the file is stored in the folder and sent the answer by json_encode.

inserir a descrição da imagem aqui

I happen to want to take the "name_file" returned by json, and save it in the BD when I submit the form. My form:

<form action="runewcode?runid=ew-assinaturas001" method="post" enctype="multipart/form-data">
(...)

<div class="col-lg-6">
    <div id="cropContainerEyecandy" style="height: 300px;"></div> <!-- ONDE É FEITO O CROP DA IMAGEM -->
</div>

(...)
</form>

I’m trying something like this to get the name_file:

<?php 
if(isset($_POST['name_file']))
{
     //GUARDA NAME_FILE NA BD
}
?>
  • You can post the Form HTML code?

  • @Diogo I’ve already edited

  • From what I see the file "img_crop_to_file.php" is what returns the JSON response. Why not store in the database at this time ?

  • @Diogo, I’m only interested in keeping it when I create the record, unless I put it in a temporary table.

  • @pc_oc, where the javascript code that makes the image post?

  • From what I see, you don’t need to make a form with enctype="multipart/form-data" because the image has already been published via ajax. When you did Crop. What you need to do is just publish the image path in the bank.

  • None of the answers answers your question?

Show 2 more comments

4 answers

1

<?php

//Exemplo
$json = '[{"status": "success","name_file": "imagemTal","url": "www.tttt.com.br/imagemTal"}]';

$jasondata =json_decode($json,true);

//Aqui você captura acessa um valor específico
echo $jasondata[0]['name_file']; exit;

echo "<pre>"; print_r($jasondata); exit;

  //  Resultado:    
  //  imagemTal


    ?>

0

In php, to get the name of a file sent via post by form, use the following:

$_FILES['name_do_input_file']['name'] //retorna o nome original do arquivo
$_FILES['name_do_input_file']['tmp_name'] // retorna o nome/destino do arquivo temporário que foi criado como upload no seu servidor

To copy the newly uploaded file, use:

copy($_FILES['name_do_input_file']['tmp_name'], "diretorio/subdiretorio/".$_FILES['name_do_input_file']['name'])

In this copy example, you can change $_FILES['name_do_input_file']['name'] to any other name you want the file to have, but you will need to treat the extension

0

Your form has the attribute multipart/form-data, which is only used when sending/moving a file to the server. This attribute is only valid for inputs of the kind type="file", and to receive the values of that input on the server side, the $_FILES, instead of $_POST which is used for other types.

Still I’m a little confused, since in the image above you already have the requisition made, and until a return, I just didn’t understand this part:

"I’m trying something like this to get the name of the picture:"

But in response to what I perceived to be the problem, since you already have the request made, and you only need to read value of the parameters contained therein, I have this example, self-explanatory.

Example:

<?php

// header("Content-Type: text/plain");
// Comentei o header para poder exibir a formatação dos echo's
$arr = array("status" => "success",
             "name_file" => "croppedImg_11647",
             "url" => "..\/publicfiles\/croppedImg_11647.png"
            );

echo "<h2>Codificar com \"json_encode()\"</h2>";            
$encode = json_encode($arr);            
echo $encode;

echo "<h2>Decodificar com \"json_encode()\"</h2>";
$decode = json_decode($encode);
echo "<p><strong>Saida (Objecto):</strong></p>";
var_dump($decode);

echo "<p><strong>Valores do objecto 1:</strong></p>";

echo $decode->status . "<br/>";
echo $decode->name_file . "<br/>";
echo $decode->url . "<br/>";

echo "<p><strong>Valores do objecto 1\":</strong></p>";
foreach($decode as $id=>$valor){
    echo "<b>{$id}</b> : " . $valor . "<br/>";        
}

echo "<p><strong>Converter os valores do objecto para uma array :</strong></p>";
foreach($decode as $id=>$valor){
    $array[$id] = $valor;
    // Ou da forma simplificada
    // $array = $valor;    
}

var_dump($array);

?>
  • That’s not really my problem. I have "inputs type="file"" because I have these fields in the form (I did not put because the form is too big). Your answer does not go according to what I want, because I want to get the name_file to save in the comic book

  • So remove the extra information, and put in the <form>..</form>.

0

If you already have a way out in json_encode() means there’s already been an upload processing, it doesn’t make much sense to recreate an upload form to send the same thing twice. Now what would make sense is to capture this JSON output in javascript and not in PHP, as you have already sent the image processing in PHP and already have the output in JSON, agree.

In case you want to handle inside PHP and save some data before exit in JSON, you need to find where this output is json_encode($array_saida) take this variable: $array_saida, and locate the key $array_saida['name_file'] before moving to Find and save the data in the database.

However, I believe that maybe you are inside a form and want to load only the reference and display this image within a form or something before performing the submission of a save form, still, there should be no enctype="multipart/form-data" on this form.

The way to capture your JSON is precisely by returning the same ajax method that made Crop of this image and generated this JSON output. As I don’t know your method I’ll give an example of return, based on this API: https://github.com/fengyuanchen/cropper

 $.ajax('/path/to/upload', {
              method: "POST",
              data: formData,
              processData: false,
              contentType: false,
              success: function (data) {
                    var e = jQuery.parseJSON(data);
                      $('#sua_imagem').attr('src', e.url); 
                      $('#img').val(e.name_file); 
               },
              error: function () {
                      console.log('Ocorreu um erro no processo!');
              }
 });

And in your HTML form:

<form action="?salvar" method="post" name="salvamento">
  <img src="undefined.jpg" id="sua_imagem" width="180" height="180" border="0">
  <input type="hidden" id="img" name="imagem"><br>
  <input type="submit" value="Enviar">
</form>
  • I won’t send the same thing twice. I upload an image, do Crop (identical to the facebook cover) and then want to save the image name

Browser other questions tagged

You are not signed in. Login or sign up in order to post.