如何使用 jQuery 异步上传文件? [英] How can I upload files asynchronously with jQuery?

查看:33
本文介绍了如何使用 jQuery 异步上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 jQuery 异步上传文件.

I would like to upload a file asynchronously with 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"/>

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

Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?

推荐答案

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

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

HTML:

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

首先,您可以根据需要进行一些验证.例如,在文件的 .on('change') 事件中:

First, you can do some validation if you want. For example, in the .on('change') event of the file:

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

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

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

现在 $.ajax() 点击按钮提交:

Now the $.ajax() submit with the button's click:

$(':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 组件并非在所有浏览器中都可用.

As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.

这篇关于如何使用 jQuery 异步上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆