如何异步上传文件?

时间:2008-10-03 10:22:17

标签: javascript jquery ajax asynchronous xmlhttprequest

我想用jQuery异步上传文件。这是我的HTML:

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

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

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

当前解决方案

我正在使用jQuery Form Plugin上传文件。

34 个答案:

答案 0 :(得分:2442)

使用HTML5,您可以使用Ajax和jQuery进行文件上传。不仅如此,您还可以使用HTML5进度标记(或div)执行文件验证(名称,大小和MIME类型)或处理progress事件。最近我不得不制作文件上传器,但我不想使用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组件。

答案 1 :(得分:254)

2019更新:仍然取决于浏览器您的人口统计用途。

使用“新”HTML5 file API了解的重要一点是wasn't supported until IE 10。如果您所针对的特定市场对旧版Windows的倾向高于平均水平,则可能无法访问它。

截至2017年,大约5%的浏览器是IE 6,7,8或9中的一个。如果您进入一家大公司(例如,这是一个B2B工具,或者您要提供培训的东西)可以火箭2016年,我与超过60%的机器使用IE8的公司打交道。

这是编辑的2019年,距我最初的答案差不多11年。 IE9及更低版本全球大约1%大关,但仍然存在更高使用率的群集。

这一点的重要内容 - 无论是什么功能,检查用户使用的浏览器。如果你不这样做,你将学到一个快速而痛苦的教训,为什么“为我工作”对于客户的交付是不够的。 caniuse是一个有用的工具,但请注意他们从中获取人口统计信息的位置。它们可能与您的不一致。这绝不比企业环境更真实。

我的答案是从2008年开始的。


但是,有一些可行的非JS文件上传方法。您可以在页面上创建一个iframe(使用CSS隐藏),然后定位表单以发布到该iframe。主页不需要移动。

这是一个“真实”的帖子,所以它不是完全互动的。如果您需要状态,则需要服务器端进行处理。这会根据您的服务器而有很大差异。 ASP.NET有更好的机制。 PHP plain失败了,但您可以使用Perl或Apache修改来解决它。

如果您需要多个文件上传,最好一次执行一个文件(以克服最大文件上传限制)。将第一个表单发布到iframe,使用上面的内容监控其进度,完成后,将第二个表单发布到iframe,依此类推。

或使用Java / Flash解决方案。他们在帖子上的表现更加灵活......

答案 2 :(得分:109)

我建议您使用Fine Uploader插件来实现此目的。您的JavaScript代码为:

$(document).ready(function() {
  $("#uploadbutton").jsupload({
    action: "addFile.do",
    onComplete: function(response){
      alert( "server response: " + response);
    }
  });
});

答案 3 :(得分:94)

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


您无法使用XMLHttpRequest(Ajax)上传文件。您可以使用iframe或Flash模拟效果。通过iframe发布文件以获得效果的优秀jQuery Form Plugin

答案 4 :(得分:87)

为未来的读者做好准备。

异步文件上传

使用HTML5

如果FormData支持File API且支持without FormData(两种HTML5功能),您可以使用$.ajax()方法上传 jQuery 文件。

您也可以发送文件Sending files using a FormData object,但无论是哪种方式,File 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 )示例,请参阅&#34; Bifröst&#34;。

后备

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

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

如果操作正确,它应该在任何浏览器上虚拟工作,但它有一些注意事项,如何从iframe获取响应。

在这种情况下,您可能更喜欢使用jQuery Ajax transport这样的包装器插件,它使用 iframe技术,但也提供允许发送文件的Bifröst 只使用$.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!");
});

插件

jQuery Form Plugin只是一个小包装器,它为jQuery的ajax方法添加了后备支持,但许多上述插件如jQuery File Upload或{{3}}包含HTML5的整个堆栈不同的后备和一些有用的功能,以简化过程。根据您的需求和要求,您可能需要考虑裸实现或其中任何一个插件。

答案 5 :(得分:83)

AJAX file upload jQuery plugin上传文件,然后传递。{ 响应回调,没有别的。

  • 它不依赖于特定的HTML,只需给它一个<input type="file">
  • 它不需要您的服务器以任何特定方式响应
  • 您使用的文件数量或页面上的位置无关紧要

- 尽量少用 -

$('#one-specific-file').ajaxfileupload({
  'action': '/upload.php'
});

- 或者与 -

一样多
$('input[type="file"]').ajaxfileupload({
  'action': '/upload.php',
  'params': {
    'extra': 'info'
  },
  'onComplete': function(response) {
    console.log('custom handler for file:');
    alert(JSON.stringify(response));
  },
  'onStart': function() {
    if(weWantedTo) return false; // cancels upload
  },
  'onCancel': function() {
    console.log('no file selected');
  }
});

答案 6 :(得分:59)

我一直在使用以下脚本上传恰好正常工作的图片。

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);
});

解释

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

最好的部分是你可以发送额外的数据,如ids&amp;使用此脚本时,使用该文件等。我在脚本中提到了extra-data

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

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

答案 7 :(得分:44)

你可以很容易地在vanilla JavaScript中完成它。这是我当前项目的一个片段:

var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
    var percent = (e.position/ e.totalSize);
    // Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
    if(this.readyState === 4) {
        // Handle file upload complete
    }
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);

答案 8 :(得分:44)

您只需使用jQuery .ajax()上传即可。

HTML:

<form id="upload-form">
    <div>
        <label for="file">File:</label>
        <input type="file" id="file" name="file" />
        <progress class="progress" value="0" max="100"></progress>
    </div>
    <hr />
    <input type="submit" value="Submit" />
</form>

CSS

.progress { display: none; }

使用Javascript:

$(document).ready(function(ev) {
    $("#upload-form").on('submit', (function(ev) {
        ev.preventDefault();
        $.ajax({
            xhr: function() {
                var progress = $('.progress'),
                    xhr = $.ajaxSettings.xhr();

                progress.show();

                xhr.upload.onprogress = function(ev) {
                    if (ev.lengthComputable) {
                        var percentComplete = parseInt((ev.loaded / ev.total) * 100);
                        progress.val(percentComplete);
                        if (percentComplete === 100) {
                            progress.hide().val(0);
                        }
                    }
                };

                return xhr;
            },
            url: 'upload.php',
            type: 'POST',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData: false,
            success: function(data, status, xhr) {
                // ...
            },
            error: function(xhr, status, error) {
                // ...
            }
       });
    }));
});

答案 9 :(得分:40)

我过去做过的最简单,最健壮的方法是简单地使用您的表单定位隐藏的iFrame标记 - 然后它将在iframe中提交而不重新加载页面。

如果你不想使用插件,JavaScript或任何其他形式的魔法&#34;除了HTML。当然,你可以将它与JavaScript或者你有什么结合......

<form target="iframe" action="" method="post" enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>

<iframe name="iframe" id="iframe" style="display:none" ></iframe>

您还可以阅读iframe onLoad的内容以了解服务器错误或成功回复,然后将其输出给用户。

Chrome,iFrame和onLoad

-note-如果您对上传/下载时如何设置UI阻止程序感兴趣,则只需继续阅读

目前,当用于传输文件时,Chrome不会触发iframe的onLoad事件。 Firefox,IE和Edge都会激活文件传输的onload事件。

我发现Chrome的唯一解决方案是使用Cookie。

基本上在上传/下载开始时这样做:

  • [客户端]开始间隔以查找是否存在cookie
  • [服务器端]使用文件数据执行您需要的任何操作
  • [服务器端]为客户端间隔设置cookie
  • [客户端] Interval查看cookie并将其用作onLoad事件。例如,您可以启动UI阻止程序然后onLoad(或者在创建cookie时)删除UI阻止程序。

为此使用cookie很难看,但它确实有用。

我下载了一个jQuery插件来处理Chrome的这个问题,你可以在这里找到

https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js

同样的基本原则也适用于上传。

使用下载程序(显然包括JS)

 $('body').iDownloader({
     "onComplete" : function(){
          $('#uiBlocker').css('display', 'none'); //hide ui blocker on complete
     }
 });

 $('somebuttion').click( function(){
      $('#uiBlocker').css('display', 'block'); //block the UI
      $('body').iDownloader('download', 'htttp://example.com/location/of/download');
 });

在服务器端,在传输文件数据之前,创建cookie

 setcookie('iDownloader', true, time() + 30, "/");

插件会看到Cookie,然后触发onComplete回调。

答案 10 :(得分:32)

我找到的解决方案是让<form>定位一个隐藏的iFrame。然后,iFrame可以运行JS以向用户显示它已完成(在页面加载时)。

答案 11 :(得分:31)

I've written this up in a Rails environment。如果你使用轻量级的jQuery-form插件,它只有大约五行JavaScript。

挑战在于让AJAX上传工作,因为标准remote_form_for不了解多部分表单提交。它不会发送文件数据Rails通过AJAX请求回寻。

这就是jQuery-form插件的用武之地。

以下是它的Rails代码:

<% remote_form_for(:image_form, 
                   :url => { :controller => "blogs", :action => :create_asset }, 
                   :html => { :method => :post, 
                              :id => 'uploadForm', :multipart => true }) 
                                                                        do |f| %>
 Upload a file: <%= f.file_field :uploaded_data %>
<% end %>

以下是相关的JavaScript:

$('#uploadForm input').change(function(){
 $(this).parent().ajaxSubmit({
  beforeSubmit: function(a,f,o) {
   o.dataType = 'json';
  },
  complete: function(XMLHttpRequest, textStatus) {
   // XMLHttpRequest.responseText will contain the URL of the uploaded image.
   // Put it in an image element you create, or do with it what you will.
   // For example, if you have an image elemtn with id "my_image", then
   //  $('#my_image').attr('src', XMLHttpRequest.responseText);
   // Will set that image tag to display the uploaded image.
  },
 });
});

这是Rails控制器动作,非常香草:

 @image = Image.new(params[:image_form])
 @image.save
 render :text => @image.public_filename

过去几周我一直在使用Bloggity,它就像一个冠军。

答案 12 :(得分:30)

简单的Ajax Uploader是另一种选择:

https://github.com/LPology/Simple-Ajax-Uploader

  • 跨浏览器 - 适用于IE7 +,Firefox,Chrome,Safari,Opera
  • 支持多个并发上传 - 即使在非HTML5浏览器中也是如此
  • 没有闪存或外部CSS - 只有一个5Kb的Javascript文件
  • 可选,内置支持完全跨浏览器进度条(使用PHP的APC扩展名)
  • 灵活且高度可定制 - 使用任何元素作为上传按钮,设置您自己的进度指示器
  • 无需任何表格,只需提供一个可用作上传按钮的元素
  • MIT许可证 - 可在商业项目中免费使用

使用示例:

var uploader = new ss.SimpleUpload({
    button: $('#uploadBtn'), // upload button
    url: '/uploadhandler', // URL of server-side upload handler
    name: 'userfile', // parameter name of the uploaded file
    onSubmit: function() {
        this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
    },
    onComplete: function(file, response) {
        // do whatever after upload is finished
    }
});

答案 13 :(得分:22)

jQuery Uploadify是我之前用过上传文件的另一个好插件。 JavaScript代码与以下内容一样简单:代码。但是,新版本在Internet Explorer中不起作用。

$('#file_upload').uploadify({
    'swf': '/public/js/uploadify.swf',
    'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
    'cancelImg': '/public/images/uploadify-cancel.png',
    'multi': true,
    'onQueueComplete': function (queueData) {
        // ...
    },
    'onUploadStart': function (file) {
        // ...
    }
});

我已经做了很多搜索,我已经找到了另一个没有任何插件上传文件的解决方案,只有ajax。解决方案如下:

$(document).ready(function () {
    $('#btn_Upload').live('click', AjaxFileUpload);
});

function AjaxFileUpload() {
    var fileInput = document.getElementById("#Uploader");
    var file = fileInput.files[0];
    var fd = new FormData();
    fd.append("files", file);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", 'Uploader.ashx');
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
             alert('success');
        }
        else if (uploadResult == 'success')
            alert('error');
    };
    xhr.send(fd);
}

答案 14 :(得分:21)

以下是另一种如何上传文件的解决方案(没有任何插件

使用简单的 Javascripts AJAX (带进度条)

HTML部分

File Pods/GoogleMaps/Frameworks/GoogleMaps.framework/Versions/A/GoogleMaps is 123.00 MB; this exceeds GitHub's file size limit of 100.00 MB

JS部分

<form id="upload_form" enctype="multipart/form-data" method="post">
    <input type="file" name="file1" id="file1"><br>
    <input type="button" value="Upload File" onclick="uploadFile()">
    <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
    <h3 id="status"></h3>
    <p id="loaded_n_total"></p>
</form>

PHP部分

function _(el){
    return document.getElementById(el);
}
function uploadFile(){
    var file = _("file1").files[0];
    // alert(file.name+" | "+file.size+" | "+file.type);
    var formdata = new FormData();
    formdata.append("file1", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "file_upload_parser.php");
    ajax.send(formdata);
}
function progressHandler(event){
    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
    var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
    _("status").innerHTML = event.target.responseText;
    _("progressBar").value = 0;
}
function errorHandler(event){
    _("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
    _("status").innerHTML = "Upload Aborted";
}

Here's the EXAMPLE application

答案 15 :(得分:15)

var formData=new FormData();
formData.append("fieldname","value");
formData.append("image",$('[name="filename"]')[0].files[0]);

$.ajax({
    url:"page.php",
    data:formData,
    type: 'POST',
    dataType:"JSON",
    cache: false,
    contentType: false,
    processData: false,
    success:function(data){ }
});

您可以使用表单数据发布所有值,包括图片。

答案 16 :(得分:13)

要使用Jquery异步上传文件,请使用以下步骤:

第1步在您的项目中打开Nuget管理器并添加包(jquery fileupload(只需要在搜索框中编写它就会出现并安装它。)) 网址:https://github.com/blueimp/jQuery-File-Upload

第2步在HTML文件中添加以下脚本,这些脚本已通过运行上面的包添加到项目中:

  

jquery.ui.widget.js

     

jquery.iframe-transport.js

     

jquery.fileupload.js

第3步按以下代码编写文件上传控件:

<input id="upload" name="upload" type="file" />

第4步将js方法写为uploadFile,如下所示:

 function uploadFile(element) {

            $(element).fileupload({

                dataType: 'json',
                url: '../DocumentUpload/upload',
                autoUpload: true,
                add: function (e, data) {           
                  // write code for implementing, while selecting a file. 
                  // data represents the file data. 
                  //below code triggers the action in mvc controller
                  data.formData =
                                    {
                                     files: data.files[0]
                                    };
                  data.submit();
                },
                done: function (e, data) {          
                   // after file uploaded
                },
                progress: function (e, data) {

                   // progress
                },
                fail: function (e, data) {

                   //fail operation
                },
                stop: function () {

                  code for cancel operation
                }
            });

        };

第5步在就绪函数调用元素文件上传中,按以下方式启动流程:

$(document).ready(function()
{
    uploadFile($('#upload'));

});

第6步按以下方式编写MVC控制器和操作:

public class DocumentUploadController : Controller
    {       

        [System.Web.Mvc.HttpPost]
        public JsonResult upload(ICollection<HttpPostedFileBase> files)
        {
            bool result = false;

            if (files != null || files.Count > 0)
            {
                try
                {
                    foreach (HttpPostedFileBase file in files)
                    {
                        if (file.ContentLength == 0)
                            throw new Exception("Zero length file!");                       
                        else 
                            //code for saving a file

                    }
                }
                catch (Exception)
                {
                    result = false;
                }
            }


            return new JsonResult()
                {
                    Data=result
                };


        }

    }

答案 17 :(得分:9)

使用| HTML5&#39; readAsDataURL()some base64 encoder将文件转换为base64。 Fiddle here

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);

答案 18 :(得分:8)

您可以使用

$(function() {
    $("#file_upload_1").uploadify({
        height        : 30,
        swf           : '/uploadify/uploadify.swf',
        uploader      : '/uploadify/uploadify.php',
        width         : 120
    });
});

Demo

答案 19 :(得分:8)

您可以通过工作演示here查看已解决的解决方案,该解决方案允许您预览表单文件并将其提交到服务器。对于您的情况,您需要使用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");

     });
   });
});

View more details

答案 20 :(得分:8)

示例:如果您使用jQuery,则可以轻松上传文件。这是一个小而强大的jQuery插件,http://jquery.malsup.com/form/

实施例

var $bar   = $('.ProgressBar');
$('.Form').ajaxForm({
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';
    $bar.width(percentVal);
  },

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';
    $bar.width(percentVal)
  },

  success: function(response) {
    // Response
  }
});

我希望它会有所帮助

答案 21 :(得分:8)

一种现代的方法没有Jquery 的方法是,当用户选择文件然后使用FileList时,使用从<input type="file">返回的Fetch对象发布包裹在FormData对象周围的FileList。

// The input DOM element
const inputElement = document.querySelector('input');

// Listen for a file submit from user
inputElement.addEventListener('change', () => {
    const data = new FormData();
    data.append('file', inputElement.files[0]);
    data.append('imageName', 'flower');

    // Post to server
    fetch('/uploadImage', {
        method: 'POST',
        body: data
    });
});

答案 22 :(得分:7)

在使用XMLHttpRequest进行异步上传时,您可以传递其他参数以及文件名(不依赖Flash和iframe)。将附加参数值附加到FormData并发送上载请求。


var formData = new FormData();
formData.append('parameter1', 'value1');
formData.append('parameter2', 'value2'); 
formData.append('file', $('input[type=file]')[0].files[0]);

$.ajax({
    url: 'post back url',
    data: formData,
// other attributes of AJAX
});

此外,Syncfusion JavaScript UI文件上传仅使用事件参数即可为该方案提供解决方案。您可以在此处找到文档here,并在此处输入有关链接的详细说明here

答案 23 :(得分:6)

在此处查找异步处理文件的上传过程https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

链接中的示例

<?php
if (isset($_FILES['myFile'])) {
    // Example:
    move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
    exit;
}
?><!DOCTYPE html>
<html>
<head>
    <title>dnd binary upload</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        function sendFile(file) {
            var uri = "/index.php";
            var xhr = new XMLHttpRequest();
            var fd = new FormData();

            xhr.open("POST", uri, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // Handle response.
                    alert(xhr.responseText); // handle response.
                }
            };
            fd.append('myFile', file);
            // Initiate a multipart/form-data upload
            xhr.send(fd);
        }

        window.onload = function() {
            var dropzone = document.getElementById("dropzone");
            dropzone.ondragover = dropzone.ondragenter = function(event) {
                event.stopPropagation();
                event.preventDefault();
            }

            dropzone.ondrop = function(event) {
                event.stopPropagation();
                event.preventDefault();

                var filesArray = event.dataTransfer.files;
                for (var i=0; i<filesArray.length; i++) {
                    sendFile(filesArray[i]);
                }
            }
        }
    </script>
</head>
<body>
    <div>
        <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
    </div>
</body>
</html>

答案 24 :(得分:3)

使用 HTML5 JavaScript ,上传异步非常简单,我创建了上传逻辑和你的html,这不是完全正常,因为它需要api,但演示它是如何工作的,如果您的网站根目录中有一个名为/upload的端点,则此代码应该适合您:

const asyncFileUpload = () => {
  const fileInput = document.getElementById("file");
  const file = fileInput.files[0];
  const uri = "/upload";
  const xhr = new XMLHttpRequest();
  xhr.upload.onprogress = e => {
    const percentage = e.loaded / e.total;
    console.log(percentage);
  };
  xhr.onreadystatechange = e => {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log("file uploaded");
    }
  };
  xhr.open("POST", uri, true);
  xhr.setRequestHeader("X-FileName", file.name);
  xhr.send(file);
}
<form>
  <span>File</span>
  <input type="file" id="file" name="file" size="10" />
  <input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>

还有一些关于XMLHttpReques的更多信息:

  

XMLHttpRequest对象

     

所有现代浏览器都支持XMLHttpRequest对象。   XMLHttpRequest对象可用于与Web交换数据   服务器幕后。这意味着可以更新   网页的一部分,无需重新加载整个页面。


  

创建XMLHttpRequest对象

     

所有现代浏览器(Chrome,Firefox,   IE7 +,Edge,Safari,Opera)都有一个内置的XMLHttpRequest对象。

     

创建XMLHttpRequest对象的语法:

     

variable = new XMLHttpRequest();


  

跨域访问

     

出于安全考虑,现代浏览器不这样做   允许跨域访问。

     

这意味着它尝试加载的网页和XML文件,   必须位于同一台服务器上。

     

W3Schools上的所有示例都是位于W3Schools上的所有开放XML文件   域。

     

如果你想在你自己的一个网页上使用上面的例子,那么   您加载的XML文件必须位于您自己的服务器上。

有关详细信息,您可以继续阅读here ...

答案 25 :(得分:3)

这是我的解决方案。

<form enctype="multipart/form-data">    

    <div class="form-group">
        <label class="control-label col-md-2" for="apta_Description">Description</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
        </div>
    </div>

    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>

和js

<script>

    $(':button').click(function () {
        var formData = new FormData($('form')[0]);
        $.ajax({
            url: '@Url.Action("Save", "Home")',  
            type: 'POST',                
            success: completeHandler,
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
    });    

    function completeHandler() {
        alert(":)");
    }    
</script>

控制器

[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
    return Json(":)");
}

答案 26 :(得分:3)

您还可以考虑使用类似https://uppy.io之类的东西。

它无需在不离开页面的情况下进行文件上传,并提供一些额外的功能,例如拖放,在浏览器崩溃/不稳定的网络情况下恢复上传以及从(例如)导入。 Instagram的。 它是开源的,不依赖jQuery / React / Angular / Vue,但可以与它一起使用。免责声明:作为创作者,我有偏见;)

答案 27 :(得分:3)

您可以使用以下代码。

async: false(true)

答案 28 :(得分:2)

您可以通过JavaScript使用较新的 Fetch API。像这样:

function uploadButtonCLicked(){
    var input = document.querySelector('input[type="file"]')

    fetch('/url', {
      method: 'POST',
      body: input.files[0]
    }).then(res => res.json())   // you can do something with response
      .catch(error => console.error('Error:', error))
      .then(response => console.log('Success:', response));
}                               

优势:所有现代浏览器都支持原生支持,因此您无需导入任何内容。另请注意,fetch()返回Promise,然后使用.then(..code to handle response..)异步处理。

答案 29 :(得分:2)

您可以使用JavaScript或jQuery进行异步多文件上传,并且无需使用任何插件即可上传。您还可以在进度控件中显示文件上传的实时进度。我遇到了2个不错的链接-

  1. ASP.NET Web Forms based Mulitple File Upload Feature with Progress Bar
  2. ASP.NET MVC based Multiple File Upload made in jQuery

服务器端语言是C#,但是您可以进行一些修改以使其与PHP等其他语言一起工作。

文件上传ASP.NET Core MVC:

在html中的视图创建文件上传控件中:

<form method="post" asp-action="Add" enctype="multipart/form-data">
    <input type="file" multiple name="mediaUpload" />
    <button type="submit">Submit</button>
</form>

现在在您的控制器中创建操作方法:

[HttpPost]
public async Task<IActionResult> Add(IFormFile[] mediaUpload)
{
    //looping through all the files
    foreach (IFormFile file in mediaUpload)
    {
        //saving the files
        string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path"); 
        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }
    }
}

hostingEnvironment变量的类型为IHostingEnvironment,可以使用依赖项注入将其注入到控制器,例如:

private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
    hostingEnvironment = environment;
}

答案 30 :(得分:2)

如果使用承诺哪个ajax并检查文件是否有效并正确保存在您的后端中怎么办,那么当用户浏览您的页面时,您可以在前面使用一些动画。

您甚至可以使用递归方法使其并发上传或堆叠

答案 31 :(得分:1)

这是一个老问题,但仍然没有答案正确答案,所以:

您是否尝试过jQuery-File-Upload

以上链接中的示例可能会解决您的问题:

$('#fileupload').fileupload({
    add: function (e, data) {
        var that = this;
        $.getJSON('/example/url', function (result) {
            data.formData = result; // e.g. {id: 123}
            $.blueimp.fileupload.prototype
                .options.add.call(that, e, data);
        });
    } 
});

答案 32 :(得分:1)

对于PHP,寻找https://developer.hyvor.com/php/image-upload-ajax-php-mysql

HTML

<html>
<head>
    <title>Image Upload with AJAX, PHP and MYSQL</title>
</head>
<body>
<form onsubmit="submitForm(event);">
    <input type="file" name="image" id="image-selecter" accept="image/*">
    <input type="submit" name="submit" value="Upload Image">
</form>
<div id="uploading-text" style="display:none;">Uploading...</div>
<img id="preview">
</body>
</html>

JAVASCRIPT

var previewImage = document.getElementById("preview"),  
    uploadingText = document.getElementById("uploading-text");

function submitForm(event) {
    // prevent default form submission
    event.preventDefault();
    uploadImage();
}

function uploadImage() {
    var imageSelecter = document.getElementById("image-selecter"),
        file = imageSelecter.files[0];
    if (!file) 
        return alert("Please select a file");
    // clear the previous image
    previewImage.removeAttribute("src");
    // show uploading text
    uploadingText.style.display = "block";
    // create form data and append the file
    var formData = new FormData();
    formData.append("image", file);
    // do the ajax part
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            var json = JSON.parse(this.responseText);
            if (!json || json.status !== true) 
                return uploadError(json.error);

            showImage(json.url);
        }
    }
    ajax.open("POST", "upload.php", true);
    ajax.send(formData); // send the form data
}

PHP

<?php
$host = 'localhost';
$user = 'user';
$password = 'password';
$database = 'database';
$mysqli = new mysqli($host, $user, $password, $database);


 try {
    if (empty($_FILES['image'])) {
        throw new Exception('Image file is missing');
    }
    $image = $_FILES['image'];
    // check INI error
    if ($image['error'] !== 0) {
        if ($image['error'] === 1) 
            throw new Exception('Max upload size exceeded');

        throw new Exception('Image uploading error: INI Error');
    }
    // check if the file exists
    if (!file_exists($image['tmp_name']))
        throw new Exception('Image file is missing in the server');
    $maxFileSize = 2 * 10e6; // in bytes
    if ($image['size'] > $maxFileSize)
        throw new Exception('Max size limit exceeded'); 
    // check if uploaded file is an image
    $imageData = getimagesize($image['tmp_name']);
    if (!$imageData) 
        throw new Exception('Invalid image');
    $mimeType = $imageData['mime'];
    // validate mime type
    $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($mimeType, $allowedMimeTypes)) 
        throw new Exception('Only JPEG, PNG and GIFs are allowed');

    // nice! it's a valid image
    // get file extension (ex: jpg, png) not (.jpg)
    $fileExtention = strtolower(pathinfo($image['name'] ,PATHINFO_EXTENSION));
    // create random name for your image
    $fileName = round(microtime(true)) . mt_rand() . '.' . $fileExtention; // anyfilename.jpg
    // Create the path starting from DOCUMENT ROOT of your website
    $path = '/examples/image-upload/images/' . $fileName;
    // file path in the computer - where to save it 
    $destination = $_SERVER['DOCUMENT_ROOT'] . $path;

    if (!move_uploaded_file($image['tmp_name'], $destination))
        throw new Exception('Error in moving the uploaded file');

    // create the url
    $protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
    $domain = $protocol . $_SERVER['SERVER_NAME'];
    $url = $domain . $path;
    $stmt = $mysqli -> prepare('INSERT INTO image_uploads (url) VALUES (?)');
    if (
        $stmt &&
        $stmt -> bind_param('s', $url) &&
        $stmt -> execute()
    ) {
        exit(
            json_encode(
                array(
                    'status' => true,
                    'url' => $url
                )
            )
        );
    } else 
        throw new Exception('Error in saving into the database');

} catch (Exception $e) {
    exit(json_encode(
        array (
            'status' => false,
            'error' => $e -> getMessage()
        )
    ));
}

答案 33 :(得分:1)

尝试

UserAction(Role.User)(customBodyParser) { implicit request => ... }
async function saveFile() 
{
    let formData = new FormData();           
    formData.append("file", file.files[0]);
    await fetch('addFile.do', {method: "POST", body: formData});    
    alert("Data Uploaded: ");
}

<span>File</span> <input type="file" id="file" name="file" size="10"/> <input type="button" value="Upload" onclick="saveFile()"/>由浏览器自动设置,文件名也被添加。这是带有err处理和json添加的更完善的示例

content-type='multipart/form-data'
async function saveFile(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user));  
    
    try {
       let r = await fetch('/upload/image', {method: "POST", body: formData}); 
       console.log('HTTP response code:',r.status); 
       alert('success');
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}