使用AJAX将文件上载到服务器

时间:2021-09-15 15:40:55

I am trying to use the approach from here to perform AJAX file upload but have no luck to get it done. I added a couple of alerts to debug and couldn't reach the 2nd break point on the following code:

我试图使用这里的方法来执行AJAX文件上传,但没有运气来完成它。我添加了几个警报进行调试,无法达到以下代码的第二个断点:

  $.validate({
    form: '#frmSlide',
    modules: 'file, html5',
    validateOnBlur: false,
    errorMessagePosition: 'top', // Instead of 'element' which is default
    scrollToTopOnError: false, // Set this property to true if you have a long form
    onSuccess: function($form) {
      alert('1');
      var file_data = $('#frmSlide').prop('files')[0];
      alert('2');
      var form_data = new FormData();
      alert('3');
      form_data.append('file', file_data);
      $.ajax({
        url: 'upload.php', // point to server-side PHP script 
        dataType: 'text', // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'post',
        success: function(php_script_response) {
          alert(php_script_response); // display response from the PHP script, if any
        }
      });
    }
  });
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSlide">

  <div class="form-group">
    <label class="col-sm-4 control-label" for="imgfile">Image file</label>
    <div class="col-sm-8">
      <input type="file" id="imgfile" data-validation="required ratio mime size" data-validation-allowing="jpg, png, gif" />
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-8 col-md-offset-4" id="image-holder">
    </div>
  </div>
  <div class="form-group">
    <label class="col-sm-4 control-label" for="seq">Sequence</label>
    <div class="col-sm-8">
      <input class="form-control server" name="f_seq" id="f_seq" data-validation="number" data-validation-allowing="range[1;4]" type="text" value="" placeholder="Enter 1-4" />
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-4 col-sm-8">
      <button name="btnUpd" id="btnUpd" type="submit" class="clsUpd btn btn-primary"><i class="fa fa-floppy-o"></i>&nbsp;Update</button>
    </div>
  </div>

</form>

Can anyone point me out what I did wrong? Thanks.

谁能指出我做错了什么?谢谢。

1 个解决方案

#1


0  

simply form doesn't have files .. but the file input have.. so you can use $('#imgfile').prop instead of $('#frmSlide').prop

简单形式没有文件..但文件输入有..所以你可以使用$('#imgfile')。prop而不是$('#frmSlide')。prop

var file_data = $('#imgfile').prop('files')[0];

#1


0  

simply form doesn't have files .. but the file input have.. so you can use $('#imgfile').prop instead of $('#frmSlide').prop

简单形式没有文件..但文件输入有..所以你可以使用$('#imgfile')。prop而不是$('#frmSlide')。prop

var file_data = $('#imgfile').prop('files')[0];