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

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


当前回答

我过去做过的最简单、最健壮的方法是,简单地将表单中隐藏的iFrame标记作为目标,然后它将在iFrame中提交,而无需重新加载页面。

这是如果你不想使用插件、JavaScript或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、iFrames和onLoad

-注意-如果你对上传/下载时如何设置UI拦截器感兴趣,你只需要继续阅读

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

我发现唯一适用于Chrome的解决方案是使用cookie。

要基本上在开始上传/下载时做到这一点:

[客户端]开始间隔以查找cookie的存在[服务器端]对文件数据执行任何需要的操作[服务器端]为客户端间隔设置cookie[Client Side]Interval查看cookie并像onLoad事件一样使用它。例如,您可以启动一个UI阻止程序,然后在加载时(或在制作cookie时)删除UI阻止程序。

用饼干做这件事很难看,但它很管用。

我制作了一个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回调。

其他回答

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

这个AJAX文件上传jQuery插件在某处上传文件,并传递对回调的响应。

它不依赖于特定的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');
  }
});

要使用Jquery异步上载文件,请执行以下步骤:

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

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

jquery.ui.widget.jsjquery.iframe-transport.jsjquery.filepload.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
                };


        }

    }

jQueryUploadify是我以前用来上传文件的另一个好插件。JavaScript代码如下所示:code。但是,新版本在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);
}

示例:如果使用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
  }
});

我希望这会有帮助