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

标签 javascript jquery ajax asynchronous xmlhttprequest

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

我只获取文件名,而不是上传文件。我该如何解决这个问题?

最佳答案

HTML5您可以使用 Ajax 和 jQuery 进行文件上传。不仅如此,您还可以进行文件验证(名称、大小和 MIME 类型)或使用 HTML5 进度标记(或 div)处理进度事件。最近要做一个文件 uploader ,但是我不想用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(和一些研究),文件上传不仅变得可能,而且 super 简单。尝试使用 Google Chrome因为示例中的某些 HTML5 组件并非在每个浏览器中都可用。

关于javascript - 如何使用 jQuery 异步上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27609212/

相关文章:

javascript - 移动 View 中的导航问题

javascript - 如何将库函数绑定(bind)到reactjs类/内容

Javascript - 用不同的值替换具有相同类的元素

javascript - 是否会使用 AJAX 发送 http_only cookie?

javascript - 如何使用 angular 和 JavaScript promise 返回一些数据?

javascript - 如何解析使用 YUI 数据源返回的 NULL 值

javascript - 云代码 - Parse.Object 初始值设定项不起作用

javascript - 单击 codeigniter 中的按钮时获取另一个页面中的 View 表值

javascript - 更改 jstree 中选定节点的颜色

javascript - 使用 Ajax HTML 输出的分页被破坏