小编典典

JavaScript如何异步上传文件?

spring

我想用jQuery异步上传文件。

$(document).ready(function () {
    $("#uploadbutton").click(function () {
        var filename = $("#file").val();

        $.ajax({
            type: "POST",
            url: "addFile.do",
            enctype: 'multipart/form-data',
            data: {
                file: filename
            },
            success: function () {
                alert("Data Uploaded: ");
            }
        });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>

我只获取文件名,而不是上传文件。我该怎么做才能解决此问题?


阅读 748

收藏
2020-04-22

共1个答案

小编典典

使用HTML5,你可以使用Ajax和jQuery进行文件上传。不仅如此,你还可以执行文件验证(名称,大小和MIME类型)或使用HTML5进度标签(或div)处理进度事件。最近,我不得不制作一个文件上传器,但是我不想使用Flash,iframes或插件,经过一番研究后,我想到了解决方案。

HTML:

<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

首先,你可以根据需要进行一些验证。例如,在.on(‘change’)文件的情况下:

$(':file').on('change', function () {
  var file = this.files[0];

  if (file.size > 1024) {
    alert('max upload size is 1k');
  }

  // Also see .name, .type
});

现在$.ajax()单击带有按钮的提交:

$(':button').on('click', function () {
  $.ajax({
    // Your server script to process the upload
    url: 'upload.php',
    type: 'POST',

    // Form data
    data: new FormData($('form')[0]),

    // Tell jQuery not to process data or worry about content-type
    // You *must* include these options!
    cache: false,
    contentType: false,
    processData: false,

    // Custom XMLHttpRequest
    xhr: function () {
      var myXhr = $.ajaxSettings.xhr();
      if (myXhr.upload) {
        // For handling the progress of the upload
        myXhr.upload.addEventListener('progress', function (e) {
          if (e.lengthComputable) {
            $('progress').attr({
              value: e.loaded,
              max: e.total,
            });
          }
        }, false);
      }
      return myXhr;
    }
  });
});

如你所见,借助HTML5(和一些研究),文件上传不仅成为可能,而且超级容易。请尝试使用Google Chrome浏览器,因为示例的某些HTML5组件并非在所有浏览器中都可用。

2020-04-22