Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

javascript - 如何异步上传文件?(How can I upload files asynchronously?)

I would like to upload a file asynchronously with jQuery.

(我想用jQuery异步上传文件。)

This is my HTML:

(这是我的HTML:)

<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>

And here my jQuery code:

(这是我的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: ");
            }
        });
    });
});

Instead of the file being uploaded, I am only getting the filename.

(我只获取文件名,而不是上传文件。)

What can I do to fix this problem?

(我该怎么做才能解决此问题?)

  ask by Sergio del Amo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With HTML5 you can make file uploads with Ajax and jQuery.

(使用HTML5,您可以使用Ajax和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).

(不仅如此,您还可以执行文件验证(名称,大小和MIME类型)或使用HTML5进度标签(或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.

(最近,我不得不制作一个文件上传器,但是我不想使用Flash ,iframe或插件,经过一番研究后,我提出了解决方案。)

The HTML:

(HTML:)

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

First, you can do some validation if you want.

(首先,您可以根据需要进行一些验证。)

For example, in the .on('change') event of the file:

(例如,在文件的.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
});

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

(现在,单击按钮即可提交$.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;
    }
  });
});

As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy.

(如您所见,借助HTML5(和一些研究),文件上传不仅成为可能,而且超级容易。)

Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.

(请尝试使用Google Chrome浏览器,因为示例的某些HTML5组件并非在每种浏览器中都可用。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...