【问题标题】:AJAX PHP upload file issueAJAX PHP 上传文件问题
【发布时间】:2017-07-01 01:58:27
【问题描述】:

我正在上传多个文件,使用在 ajax 中添加更多文件并将其保存在 php 中的数据库中。但它只插入数据库中的最后一个文件,而不是数据库中的多个文件。

HTML 代码

<form id="registration_form" method="post" enctype="multipart/form-data">
   <input type="file"   id="file" name="file[]">
   <input type="button" id="add_more" class="upload" value="Add More Files"/>
</form>

AJAX 代码

$(document).ready(function() {
    //  To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
    $('#add_more').click(function() {
    $(this).before($("
    <div id='filediv'/>
    ").append($("<input name='file[]' type='file' id='file'>"
    )));
    $.ajax({
    url:"update.php",
    type:"post",
    data: new FormData(this),
    contentType:false,
    cache:false,
    processData:false,
    success:function(data)
    {
    alert(data);
    },
    failure:function(errormsg)
    {
    alert(errormsg);
    }
    });
});`

PHP 代码

 <!------- Including PHP Script here ------>
 <?php if (isset($_POST['submit'])) {
   $j = 0;     // Variable for indexing uploaded image.
   $target_path = "upload/";     // Declaring Path for uploaded images.
   for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
   // Loop to get individual element from the array
   $validextensions = array("jpeg", "jpg", "png");      // Extensions which are allowed.
   $ext = explode('.', basename($_FILES['file']['name'][$i]));   // Explode file name from dot(.)
   $file_extension = end($ext); // Store extensions in the variable.
   $target_path = $target_path  . $_FILES['file']['name'][$i];  
   //echo $target_path; die;   // Set the target path with a new name of image.
   $j = $j + 1;      // Increment the number of uploaded images according to the files in array.
   if (($_FILES["file"]["size"][$i] < 800000)     // Approx. 800kb files can be uploaded.
   && in_array($file_extension, $validextensions)) {
   if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
   // If file moved to uploads folder.
   echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
   } else {     //  If File Was Not Moved.
   echo $j. ').<span id="error">please try again!.</span><br/><br/>';
   }
   } else {     //   If File Size And File Type Was Incorrect.
   echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
   }
   }
   } ?>

【问题讨论】:

  • 请正确格式化您的问题。
  • 我无法格式化问题你能格式化我的问题吗

标签: php jquery ajax upload


【解决方案1】:

您需要将所有文件附加到表单数据中。试试这个

var data = new FormData();

$.each($("input[type='file']")[0].files, function(i, file) {
    data.append('file', file);
});

将此数据变量传递给 ajax 数据。

【讨论】:

  • 当我在 ajax 成功警告数据时不工作我只有第一次上传文件名。这是我的 php 代码
  • 请回答这个问题
猜你喜欢
  • 2011-10-11
  • 2011-07-22
  • 2010-11-12
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多