如何为图片上传器添加进度栏?

时间:2019-09-12 08:44:47

标签: php jquery ajax

我正在为图像创建一个上传器,我想添加一个带有进度标签的进度条,并且百分比将写在进度条下方。

<div class="container">
  <form action="multipart/form-data">
    <div id="preview"><img src="" id="prev_img" width="100%" height='100%'></div>
    <input type="file" name="file" id="file">
  </form>
</div>
$(document).ready(function() {
  var _URL = window.URL || window.webkitURL

  $('#file').change(function() {
    var file = $(this)[0].files[0]

    img = new Image()
    var imgwidth = 0
    var imgheight = 0
    var minwidth = 640
    var minheight = 320

    img.src = _URL.createObjectURL(file)
    img.onload = function() {
      imgwidth = this.width
      imgheight = this.height

      $("#width").text(imgwidth)
      $("#height").text(imgheight)

      if (imgwidth >= minwidth && imgheight >= minheight) {
        var formData = new FormData()
        formData.append('fileToUpload', $('#file')[0].files[0])

        $.ajax({
          url: './upload.php',
          type: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          dataType: 'json',
          success: function(response) {
            if (response.status == 1) {
              $("#prev_img").attr("src", "upload/" + response.returnText)
              $("#prev_img").show()
              $("#response").text("Upload successfully")
            } else {
              alert(response.returnText)
            }
          }
        })
      } else {
        alert("Sorry, this image is too small or of too low a quality, please try again with another image of better quality, minimum 640X320 pixels or more. We suggest that you submit the original version of your recent photos that have not been reduced or retouched.")
      }
    }
    img.onerror = function() {
      $("#response").text("not a valid file: " + file.type)
    }
  })
})

0 个答案:

没有答案