【问题标题】:how to upload multiple image in php using javascript array如何使用javascript数组在php中上传多个图像
【发布时间】:2017-09-10 09:05:24
【问题描述】:

我在 java 脚本中有一个数组,该数组有文件名和文件路径,现在我必须在 php 中分配该数组并上传存储在数组中的文件,我该怎么办,请给我解决方案。

这是我的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 是我的数组,如何在 php 中分配该数组并上传到文件中, 您可以在控制台中检查以获取值

php 文件

<!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>

每当点击clickMe按钮时,您可以在控制台中检查文件名和文件路径,请帮助我

【问题讨论】:

  • 表单发布请求发送到哪里?
  • @elpddev 先生,没有表格是主要原因,我该怎么办?
  • 可以使用 Javascript 通过为每个由您的 JS 函数创建的 span 元素创建 &lt;input name="yourName" type="hidden" value="someValue"/&gt; 来完成。然后通过$_POST['yourName'] 从另一个 php 文件中获取值。但要做到这一点,我们必须知道您想先发送哪些值。目前有两个值 ID 和图像路径。你想把它们都寄出去吗?
  • 此外,该输入值应存储一个数组,其中包含您要发送的值。为此,您的 JS 代码必须改进。
  • @Rüzgar 先生,每当我将存储在文本框中时,只会得到一个值,这是最后一个值,我只想存储文件名和路径

标签: javascript php html


【解决方案1】:

抱歉,迟到了。我不是 100% 确定这是否是你想要的。但我还是这样做了:)。感谢@Ben_Lee 和他的answer,我设法将启动包装在一个函数中。

    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>

在这里,我创建了一个隐藏输入,用于存储数组。

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

然后为表单分配一个动作以将数据发送到另一个php文件。

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

现在是时候获取数据和处理了:

<?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>";
}
?>

希望对您有所帮助,如果您还有其他问题,请随时提问。

【讨论】:

    猜你喜欢
    • 2022-10-19
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2017-05-21
    相关资源
    最近更新 更多