使用百分比更换器上传Jquery Ajax文件

时间:2018-02-23 08:37:03

标签: javascript jquery file-upload jquery-file-upload

$(document).ready(function() {


  $('#upload-btn').on('click', function() {


    $('#upload-input').click();
    $('.progress-bar').text('0%');
    $('.progress-bar').width('0%');

    $('#upload-input').on('change', function() {
      var uploadInput = $('#upload-input').val(); 

      if (uploadInput != '') {
        var formData = new FormData();
        console.log(uploadInput[0]);
        formData.append('upload', uploadInput[0].files[0]).val();

        $.ajax({
          url: '/upload',
          type: 'POST',
          data: formData,
          processType: false,
          contentType: false,
          success: function(data) {
            $('#upload-input').val('');
          },
          xhr: function() {
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function(e) {

              if (e.lengthComputable) {
                var uploadPercent = e.loaded / e.total;
                uploadpercent = (uploadpercent * 100);
                $('.progress-bar').text(uploadpercent + '%');
                $('.progress-bar').width(uploadpercent + '%');

                if (uploadpercent == 100) {
                  $('.progress-bar').text('Completed');
                }
              }
            }, false);

            return xhr;
          }
        })
      }
    });
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" rel="stylesheet" type="text/css" > 
<form method="POST" action="/company/create">

  <div class="form-group ">
    <label for="">Company Name</label>
    <span id="errorMsg1"></span>
    <input id="name" class="form-control" name="name" type="text" style="margin-bottom:20px;">
  </div>

  <div class="form-group ">
    <label for="">Address</label>
    <span id="errorMsg2"></span>
    <input id="address" class="form-control" name="address" type="text" style="margin-bottom:20px;">
  </div>

  <div class="form-group ">
    <label for="">City</label>
    <span id="errorMsg3"></span>
    <input id="city" class="form-control" name="city" type="text" style="margin-bottom:20px;">
  </div>

  <div class="form-group ">
    <label for="">Country</label>
    <span id="errorMsg4"></span>
    <input id="country" class="form-control" name="country" type="text" style="margin-bottom:20px;">
  </div>

  <div class="form-group ">
    <label for="">Sector</label>
    <span id="errorMsg5"></span>
    <input id="sector" class="form-control" name="sector" type="text" style="margin-bottom:20px;">
  </div>

  <div class="form-group ">
    <label for="">Website</label>
    <span id="errorMsg6"></span>
    <input id="website" class="form-control" name="website" type="text" style="margin-bottom:20px;">
  </div>

  <div class="form-group ">
    <label for="">Company Image</label><br>

    <button class="btn btn-lg" type="button" data-toggle="modal" data-target="#file">Add File</button>
    <span id="completed"></span>

    <div id="file" class="modal" tabindex="-1" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" id="close" class="close" data-dismiss="modal">&times;</button>
            <div class="modal-title">Upload Image</div>
          </div>

          <div class="modal-body">
            <div class="row">
              <div class="progress">
                <div class="progress-bar" role="progressbar"></div>
              </div>

              <button class="btn btn-lg upload-btn" id="upload-btn" " type="button ">Upload File</button>
                                            <input type="file " class="form-control " name="upload " id="upload-input " style="display:none ">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                    </div>


                    <div class="form-group ">
                        <input type="submit " id="register " value="Register " class="form-control btn btn-primary " name="register " style=" ">
                    </div>

                </form>

var uploadInput = $('#upload-input')。val();

  

这里uploadInput只有文件路径,所以会发生什么   当我尝试使用uploadInput [0] .files [0]访问该文件时   我收到以下错误   无法读取未定义的属性“0”

为什么会发生这种情况&gt;?

  if (uploadInput != '') {
    var formData = new FormData();
    console.log(uploadInput[0]);
    formData.append('upload', uploadInput[0].files[0]);

1 个答案:

答案 0 :(得分:0)

你错过了这个

var uploadInput = $('#upload-input').val();var uploadInput = $('#upload-input');

processType: false,processData: false,

和错字

uploadPercentuploadpercent

剩下的就是作品

&#13;
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" rel="stylesheet" type="text/css" > 


<form method="POST" action="/company/create">

	<div class="progress">
		<div class="progress-bar" role="progressbar"></div>
	</div>
	<button class="btn btn-lg upload-btn" id="upload-btn" type="button">Upload File</button>
	<input type="file" class="form-control" name="upload" id="upload-input" >
	
</form>


<script>
$(document).ready(function() {

	$('#upload-input').change(function(){
		$('.progress-bar').text('0%');
		$('.progress-bar').width('0%');
	});
	$('#upload-btn').on('click', function() {
		$('.progress-bar').text('0%');
		$('.progress-bar').width('0%');
		var uploadInput = $('#upload-input'); 

		if (uploadInput[0].files[0] != undefined) {
			var formData = new FormData();
			formData.append('upload', uploadInput[0].files[0]);

			$.ajax({
				url: '/upload',
				type: 'POST',
				data: formData,
				//processType: false, WRONG syntax
				processData: false,
				contentType: false,
				success: function(data) {
					$('#upload-input').val('');
				},
				xhr: function() {
					var xhr = new XMLHttpRequest();
					xhr.upload.addEventListener("progress", function(e) {
						if (e.lengthComputable) {
							//var uploadPercent = e.loaded / e.total; typo uploadpercent (all lowercase)
							var uploadpercent = e.loaded / e.total; 
							uploadpercent = (uploadpercent * 100); //optional Math.round(uploadpercent * 100)
							$('.progress-bar').text(uploadpercent + '%');
							$('.progress-bar').width(uploadpercent + '%');
							if (uploadpercent == 100) {
								$('.progress-bar').text('Completed');
							}
						}
					}, false);
					
					return xhr;
				}
			})
		}
    });
});
</script>
&#13;
&#13;
&#13;