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

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


当前回答

我已经在Rails环境中编写了这篇文章。如果您使用轻量级的jQuery表单插件,它只有大约五行JavaScript。

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

这就是jQuery表单插件发挥作用的地方。

下面是它的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上使用这个,它的效果就像一个冠军。

其他回答

在使用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文件上传只需使用事件参数即可为该场景提供解决方案。您可以在此处找到文档,并在此处输入链接描述

您可以通过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 API,因此您不必导入任何内容。此外,请注意,fetch()返回Promise,然后使用.then(..代码处理响应..)异步处理Promise。

要使用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);
}

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