简体   繁体   English

使用Ajax和PHP上传音频文件

[英]Upload audio file using Ajax and PHP

I am trying to upload an audio file. 我正在尝试上传音频文件。

What am doing is passing the audio file through Ajax to PHP where the upload and other insert to my database will be done. 这样做是通过Ajax将音频文件传递给PHP,然后将音频文件上传和插入到我的数据库中。

After passing it through Ajax, my PHP page does not see the audio file. 通过Ajax传递之后,我的PHP页面看不到音频文件。

<script type="text/javascript">
$(function () {

  $('form').on('submit', function (e) {

    e.preventDefault();

    document.getElementById("load").style.display = "block";
    textarea = $('#editor-one').html();
    var formData = new FormData($(this)[0]);
    formData.append("content", textarea);

    $.ajax({
      type: 'post',
      url: 'verimg.php?ins=newmu',
      data: formData,

      cache: false,
      contentType: false,
      processData: false,
      success: function(data){
        document.getElementById("load").style.display = "none";
        //alert(textarea);
        jQuery('#get_result').html(data).show();
      }
    });
  });
});

  </script>

Here is my PHP code: 这是我的PHP代码:

if(!isset($_FILES['file'])){
  echo '<div class="alert alert-warning">
          <strong>Warning!</strong> Please select an audio
        </div>';
}else{
  $uploaderror='';
  $name = ucfirst($_POST['name']);
  $artist = $_POST['artist'];
  $content = $_POST['content'];
  $genre = $_POST['genre'];

  $validator = new FormValidator();
  $validator->addValidation("name","req","Please fill in Music Name");
  $validator->addValidation("category","req","Please Select Artist");
  $validator->addValidation("category","req","Please Select Genre");
}

I always get "Warning! Please select an audio". 我总是收到“警告!请选择音频”。

I have made changes to your formData. 我对您的formData进行了更改。 In your php code you are trying to check the 'file' key in your global $_FILES variable but in your formData variable the audio file isn't attached to any 'key'. 在您的php代码中,您尝试检查全局$ _FILES变量中的“文件”键,但在formData变量中,音频文件未附加到任何“键”。 Hope it works :) 希望它能工作:)

<script type="text/javascript">
 $(function () {

$('form').on('submit', function (e) {

  e.preventDefault();

  document.getElementById("load").style.display = "block";
  textarea = $('#editor-one').html();
  var formData = new FormData();
  formData.append("file", e.target.files[0]);
  $.ajax({
    type: 'post',
    url: 'verimg.php?ins=newmu',
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data)
    {
        document.getElementById("load").style.display = "none";
        //alert(textarea);
        jQuery('#get_result').html(data).show();
    }
  });

});

});

</script>

Try to add enctype='multipart/form-data' to your form tag. 尝试将enctype='multipart/form-data'到您的form标签中。
;) ;)

A long painfull Reference is here. 冗长的参考书在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM