我想用jQuery异步上传文件。

$(文档).ready(函数(){$(“#uploadbutton”).click(函数(){var filename=$(“#file”).val();$.ajax美元({类型:“POST”,url:“addFile.do”,enctype:'多部分/表单数据',数据:{文件:文件名},成功:函数(){alert(“上传的数据:”);}});});});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js“></script><span>文件</span><input type=“file”id=“file”name=“file”size=“10”/><input id=“uploadbutton”type=“button”value=“Upload”/>

我只得到文件名,而不是上传文件。我可以做什么来解决这个问题?


当前回答

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

其他回答

使用|HTML5的readAsDataURL()或一些base64编码器将文件转换为base64。在这里摆弄

var reader = new FileReader();

        reader.onload = function(readerEvt) {
            var binaryString = readerEvt.target.result;
            document.getElementById("base64textarea").value = btoa(binaryString);
        };

        reader.readAsBinaryString(file);

然后检索:

window.open("data:application/octet-stream;base64," + base64);

注意:此答案已过时,现在可以使用XHR上载文件。


不能使用XMLHttpRequest(Ajax)上载文件。可以使用iframe或Flash模拟效果。优秀的jQuery表单插件,通过iframe发布文件以获得效果。

您可以在这里看到一个工作演示的解决方案,该演示允许您预览表单文件并将其提交到服务器。对于您的情况,您需要使用Ajax来促进文件上传到服务器:

<from action="" id="formContent" method="post" enctype="multipart/form-data">
    <span>File</span>
    <input type="file" id="file" name="file" size="10"/>
    <input id="uploadbutton" type="button" value="Upload"/>
</form>

提交的数据是表单数据。在jQuery上,使用表单提交函数而不是单击按钮提交表单文件,如下所示。

$(document).ready(function () {
   $("#formContent").submit(function(e){

     e.preventDefault();
     var formdata = new FormData(this);

 $.ajax({
     url: "ajax_upload_image.php",
     type: "POST",
     data: formdata,
     mimeTypes:"multipart/form-data",
     contentType: false,
     cache: false,
     processData: false,
     success: function(){

     alert("successfully submitted");

     });
   });
});

查看更多详细信息

为未来读者整理。

异步文件上载

使用HTML5

如果支持FormData和File API(这两个HTML5功能),则可以使用$.ajax()方法使用jQuery上载文件。

您也可以在不使用FormData的情况下发送文件,但无论哪种方式,文件API都必须以XMLHttpRequest(Ajax)发送的方式处理文件。

$.ajax({
  url: 'file/destination.html', 
  type: 'POST',
  data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.
  processData: false,
  contentType: false                    // Using FormData, no need to process data.
}).done(function(){
  console.log("Success: Files sent!");
}).fail(function(){
  console.log("An error occurred, the files couldn't be sent!");
});

有关快速纯JavaScript(无jQuery)示例,请参阅“使用FormData对象发送文件”。

退路

当HTML5不受支持(没有文件API)时,唯一的其他纯JavaScript解决方案(没有Flash或任何其他浏览器插件)是隐藏的iframe技术,它允许在不使用XMLHttpRequest对象的情况下模拟异步请求。

它包括使用文件输入将iframe设置为表单的目标。当用户提交请求并上传文件时,响应显示在iframe中,而不是重新呈现主页。隐藏iframe使整个过程对用户透明,并模拟异步请求。

如果处理得当,它实际上应该可以在任何浏览器上运行,但它对如何从iframe中获取响应有一些警告。

在这种情况下,您可能更喜欢使用像Bifröst这样的包装器插件,它使用iframe技术,但也提供jQueryAjax传输,允许仅使用$.Ajax()方法发送文件,如下所示:

$.ajax({
  url: 'file/destination.html', 
  type: 'POST',
  // Set the transport to use (iframe means to use Bifröst)
  // and the expected data type (json in this case).
  dataType: 'iframe json',                                
  fileInputs: $('input[type="file"]'),  // The file inputs containing the files to send.
  data: { msg: 'Some extra data you might need.'}
}).done(function(){
  console.log("Success: Files sent!");
}).fail(function(){
  console.log("An error occurred, the files couldn't be sent!");
});

插件

Bifröst只是一个小包装,它为jQuery的ajax方法添加了回退支持,但前面提到的许多插件,如jQuery表单插件或jQuery文件上载,都包括从HTML5到不同回退的整个堆栈,以及一些有用的功能来简化过程。根据您的需要和要求,您可能需要考虑一个简单的实现或其中一个插件。

我一直在使用下面的脚本来上传图像,这很好。

HTML

<input id="file" type="file" name="file"/>
<div id="response"></div>

JavaScript

jQuery('document').ready(function(){
    var input = document.getElementById("file");
    var formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    input.addEventListener("change", function (evt) {
        var i = 0, len = this.files.length, img, reader, file;

        for ( ; i < len; i++ ) {
            file = this.files[i];

            if (!!file.type.match(/image.*/)) {
                if ( window.FileReader ) {
                    reader = new FileReader();
                    reader.onloadend = function (e) {
                        //showUploadedItem(e.target.result, file.fileName);
                    };
                    reader.readAsDataURL(file);
                }

                if (formdata) {
                    formdata.append("image", file);
                    formdata.append("extra",'extra-data');
                }

                if (formdata) {
                    jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');

                    jQuery.ajax({
                        url: "upload.php",
                        type: "POST",
                        data: formdata,
                        processData: false,
                        contentType: false,
                        success: function (res) {
                         jQuery('div#response').html("Successfully uploaded");
                        }
                    });
                }
            }
            else
            {
                alert('Not a vaild image!');
            }
        }

    }, false);
});

解释

我使用response div显示上传动画和上传完成后的响应。

最好的部分是,当您使用此脚本时,可以随文件发送额外的数据,如id等。我在脚本中提到了额外的数据。

在PHP级别,这将作为正常的文件上传工作。额外数据可以作为$_POST数据检索。

这里你没有使用插件之类的东西。您可以根据需要更改代码。你不是盲目地在这里编码。这是任何jQuery文件上传的核心功能。实际上是Javascript。