1

i have an array in java script, that array have file name and file path, now i have to assign that array in php and upload that file which are store in array, what can i do please give me solutions.

This is my javascript

<script type="text/javascript">

    var arrImgNPath = [];
    var arrUniqueIds = [];

    function myFunction() {

        var files = $('#filesID').prop("files");
        var names = $.map(files, function(val) { return val.name; });

        console.log(names);
        console.log("N the final result is :");

        for (var i=0; i<arrImgNPath.length; i++){

            var dict = arrImgNPath[i];
            //$('#str').val(JSON.stringify(dict)); 

            console.log("obj value :",dict);

        }

    }

    function removeImageDataFromArray(spanId){

        console.log("spanID--------------------------------------"+spanId);

        arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; }); 

        for (var i=0; i<arrImgNPath.length; i++){

            var dict = arrImgNPath[i];
            console.log("obj value :",dict);

        }

    }

    function uniqId() {

        while (1) {

            var uid = Math.round(new Date().getTime() + (Math.random() * 100));

            var isPresent = false;

            for(var i=0; i<arrUniqueIds.length; i++){
                var idFromArray = arrUniqueIds[i];
                if (uid == idFromArray){
                    isPresent = true;
                }
            }

            if (isPresent === false) {
                return uid;

            }
        }

    }

    $(document).ready(function() {
  if (window.File && window.FileList && window.FileReader) {

    $("#filesID").on("change", function(e) {
      var files = e.target.files,
        filesLength = files.length;


        //console.log(files);

        var filePath = $(this).val();
            //console.log("fake pathddddddddddd"+filePath);

      for (var i = 0; i < filesLength; i++) {


        var tmppath = URL.createObjectURL(event.target.files[0]);
        filePath =tmppath;

        var f = files[i];

        var randomId = uniqId();

        var dict = {};


        dict.name = f.name;
        dict.path = filePath;
        dict.ID = randomId;
        arrImgNPath[arrImgNPath.length] = dict;

        var fileReader = new FileReader();


        fileReader.onload = (function(e) {

          var file = e.target;
          //console.log("bfsd dsf sdfdsfds"+e.target.result);

        //  console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);


          $("<span  id=\"" + randomId + "\"  class=\"pip\" >" +
            "<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
            "<br/><span class=\"remove\">Remove image</span>" +
            "</span>").insertAfter("#filesID");

          $(".remove").click(function(){
            //$(this).find("span").attr("id", "myspan_"+i);
            console.log("files id values :"+ $(this).parent(".pip").attr("id"));
            removeImageDataFromArray($(this).parent(".pip").attr("id"));    
            $(this).parent(".pip").remove();
          });

        });

        fileReader.readAsDataURL(f);
      }
    });
  } else {
    alert("Your browser doesn't support to File API");
  }
});

    </script>

dict is my array how can assign that array in php and upload in file, you can check in console to gat the value

php file

<!DOCTYPE html>

    <head>
        <style>
            input[type="file"] {
  display: block;
}
.imageThumb {
  max-height: 75px;
  border: 2px solid;
  padding: 1px;
  cursor: pointer;
}
.pip {
  display: inline-block;
  margin: 10px 10px 0 0;
}
.remove {
  display: block;
  background: #444;
  border: 1px solid black;
  color: white;
  text-align: center;
  cursor: pointer;
}
.remove:hover {
  background: white;
  color: black;
}
        </style>
    </head>

    <body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post"  enctype="multipart/form-data" >
  <h3>Upload your images</h3>
   <input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >

  <input type="submit" name="submit" >
  <input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>

whenever click the clickMe button you can the file name and file path in console check it and please help me

Varin
  • 2,354
  • 2
  • 20
  • 37
  • Where does to form post request get sent to ? – elpddev Apr 14 '17 at 07:29
  • @elpddev sir there is no form that is the main reason, how can i do it? – Dharmendra Kakde Apr 14 '17 at 12:55
  • It can be done using Javascript by creating `` for each span elements which are created by your JS function. And then get the values from another php file by `$_POST['yourName']`. But to do this, we have to know which values you would like to send first. Currently there are two values ID and image path. Would you like to send them both? – Rüzgar Apr 14 '17 at 15:21
  • Also, that input value should store an array including the values you would like to send. And to do that, your JS code should have to be improved. – Rüzgar Apr 14 '17 at 15:44
  • @Rüzgar sir, whenever i will store in textbox that time get only one value and that is last value and i want store only file name and path – Dharmendra Kakde Apr 15 '17 at 09:02
  • Ok, i will try on my computer, and get back to you as soon as possible. – Rüzgar Apr 15 '17 at 10:21
  • ok Thank You @Rüzgar Sir... – Dharmendra Kakde Apr 15 '17 at 10:56

1 Answers1

0

Sorry for the late return. I am not 100% sure if this is what you wanted. But i did it anyway :). Thanks to @Ben_Lee with his answer I managed to wrap the initiation inside a function.

    var arrImgNPath = [];
    var arrUniqueIds = [];

    function myFunction() {

        var files = $('#filesID').prop("files");
        var names = $.map(files, function(val) { return val.name; });

        console.log(names);
        console.log("N the final result is :");

        for (var i=0; i<arrImgNPath.length; i++){

            var dict = arrImgNPath[i];
            //$('#str').val(JSON.stringify(dict)); 

            console.log("obj value :",dict);

        }

    }

    function removeImageDataFromArray(spanId){

        console.log("spanID--------------------------------------"+spanId);

        arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; }); 

        for (var i=0; i<arrImgNPath.length; i++){

            var dict = arrImgNPath[i];
            console.log("obj value :",dict);

        }

    }

    function uniqId() {

        while (1) {

            var uid = Math.round(new Date().getTime() + (Math.random() * 100));

            var isPresent = false;

            for(var i=0; i<arrUniqueIds.length; i++){
                var idFromArray = arrUniqueIds[i];
                if (uid == idFromArray){
                    isPresent = true;
                }
            }

            if (isPresent === false) {
                return uid;

            }
        }

    }
    function initiateFiles(file) {


        var tmppath = URL.createObjectURL(event.target.files[0]);
        filePath =tmppath;

        var f = file;

        var randomId = uniqId();

        var dict = {};


        dict.name = f.name;
        dict.path = filePath;
        dict.ID = randomId;
        arrImgNPath[arrImgNPath.length] = dict;

        var fileReader = new FileReader();


        fileReader.onload = (function(e) {

          //var file = e.target;
          //console.log("bfsd dsf sdfdsfds"+e.target.result);

        //  console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);


        $("<span  id=\"" + randomId + "\"  class=\"pip\" >" +
            "<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
            "<br/><span class=\"remove\">Remove image</span>" +
            "</span>").insertAfter("#filesID");

        $(".remove").click(function(){
            //$(this).find("span").attr("id", "myspan_"+i);
            console.log("files id values :"+ $(this).parent(".pip").attr("id"));
            removeImageDataFromArray($(this).parent(".pip").attr("id"));    
            $(this).parent(".pip").remove();
        });

    });

        fileReader.readAsDataURL(f);
    }

    $(document).ready(function() {
      if (window.File && window.FileList && window.FileReader) {

        $("#filesID").on("change", function(e) {
          var files = e.target.files,
          filesLength = files.length;



          var filePath = $(this).val();
          for (var i = 0; i < filesLength; i++) {
            initiateFiles(files[i]);
        }
        console.log(arrImgNPath);
        var myJSON = JSON.stringify(arrImgNPath);
        
        $("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
    });
    } else {
        alert("Your browser doesn't support to File API");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post"  action="yourOther.php" enctype="multipart/form-data" >
  <h3>Upload your images</h3>
   <input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
  <input type="submit" name="submit" >
  <input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>

Here i created a hidden input, which stores the array.

$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");

And then assigned an action to the form to send the data to another php file.

<form method="post" action="yourOther.php" enctype="multipart/form-data" >

And now it is time to get the data and process:

<?php
$data = json_decode($_POST['myJSON']);

foreach ($data as $key => $value) {
    echo " Name : $value->name <hr>";
    echo " Path : $value->path <hr>";
    echo " ID : $value->ID <hr>";
}
?>

I hope this helps, if you have further questions, don't hesitate to ask.

Community
  • 1
  • 1
Rüzgar
  • 947
  • 9
  • 20