小编典典

如何使用 jQuery 异步上传文件?

javascript

我想用 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"/>

我只获取文件名,而不是上传文件。我能做些什么来解决这个问题?


阅读 155

收藏
2022-01-21

共1个答案

小编典典

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

的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 组件并非在每个浏览器中都可用。

2022-01-21