使用Ajax以一种形式上传数据和文件吗?

本文翻译自:Uploading both data and files in one form using Ajax?

I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form? 我正在为表单使用jQuery和Ajax来提交数据和文件,但是我不确定如何以一种形式发送数据和文件?

I currently do almost the same with both methods but the way in which the data is gathered into an array is different, the data uses .serialize(); 我目前对这两种方法几乎相同,但是将数据收集到数组中的方式不同,数据使用.serialize(); but the files use = new FormData($(this)[0]); 但是文件使用= new FormData($(this)[0]);

Is it possible to combine both methods to be able to upload files and data in one form through Ajax? 是否可以将两种方法结合起来以通过Ajax以一种形式上载文件和数据?

Data jQuery, Ajax and html 数据jQuery,Ajax和html

$("form#data").submit(function(){

    var formData = $(this).serialize();

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
});

<form id="data" method="post">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <button>Submit</button>
</form>

Files jQuery, Ajax and html 文件jQuery,Ajax和html

$("form#files").submit(function(){

    var formData = new FormData($(this)[0]);

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
});

<form id="files" method="post" enctype="multipart/form-data">
    <input name="image" type="file" />
    <button>Submit</button>
</form>

How can I combine the above so that I can send data and files in one form via Ajax? 如何结合以上内容,以便可以通过Ajax以一种形式发送数据和文件?

My aim is to be able to send all of this form in one post with Ajax, is it possible? 我的目标是能够通过Ajax在一个帖子中发送所有此表格,这可能吗?

<form id="datafiles" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <button>Submit</button>
</form>

#1楼

参考:https://stackoom.com/question/jjQW/使用Ajax以一种形式上传数据和文件吗


#2楼

The problem I had was using the wrong jQuery identifier. 我遇到的问题是使用了错误的jQuery标识符。

You can upload data and files with one form using ajax . 可以 使用ajax以一种形式上载数据和文件

PHP + HTML PHP + HTML

<?php

print_r($_POST);
print_r($_FILES);
?>

<form id="data" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <button>Submit</button>
</form>

jQuery + Ajax jQuery + Ajax

$("form#data").submit(function(e) {
    e.preventDefault();    
    var formData = new FormData(this);

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });
});

Short Version 简洁版本

$("form#data").submit(function(e) {
    e.preventDefault();
    var formData = new FormData(this);    

    $.post($(this).attr("action"), formData, function(data) {
        alert(data);
    });
});

#3楼

Or shorter: 或更短:

$("form#data").submit(function() {
    var formData = new FormData(this);
    $.post($(this).attr("action"), formData, function() {
        // success    
    });
    return false;
});

#4楼

another option is to use an iframe and set the form's target to it. 另一种选择是使用iframe并为其设置表单目标。

you may try this (it uses jQuery): 您可以尝试一下(它使用jQuery):

function ajax_form($form, on_complete)
{
    var iframe;

    if (!$form.attr('target'))
    {
        //create a unique iframe for the form
        iframe = $("<iframe></iframe>").attr('name', 'ajax_form_' + Math.floor(Math.random() * 999999)).hide().appendTo($('body'));
        $form.attr('target', iframe.attr('name'));
    }

    if (on_complete)
    {
        iframe = iframe || $('iframe[name="' + $form.attr('target') + '"]');
        iframe.load(function ()
        {
            //get the server response
            var response = iframe.contents().find('body').text();
            on_complete(response);
        });
    }
}

it works well with all browsers, you don't need to serialize or prepare the data. 它适用于所有浏览器,无需序列化或准备数据。 one down side is that you can't monitor the progress. 不利的一面是您无法监控进度。

also, at least for chrome, the request will not appear in the "xhr" tab of the developer tools but under "doc" 而且,至少对于chrome,该请求不会出现在开发者工具的“ xhr”标签中,而是在“ doc”下


#5楼

I was having this same issue in ASP.Net MVC with HttpPostedFilebase and instead of using form on Submit I needed to use button on click where I needed to do some stuff and then if all OK the submit form so here is how I got it working 我在带有HttpPostedFilebase的ASP.Net MVC中遇到了同样的问题,而不是在Submit上使用表单,我需要在需要做一些事情的地方单击按钮,然后如果一切正常,那么提交表单就可以了,这就是我的工作方式

$(".submitbtn").on("click", function(e) {

    var form = $("#Form");

    // you can't pass Jquery form it has to be javascript form object
    var formData = new FormData(form[0]);

    //if you only need to upload files then 
    //Grab the File upload control and append each file manually to FormData
    //var files = form.find("#fileupload")[0].files;

    //$.each(files, function() {
    //  var file = $(this);
    //  formData.append(file[0].name, file[0]);
    //});

    if ($(form).valid()) {
        $.ajax({
            type: "POST",
            url: $(form).prop("action"),
            //dataType: 'json', //not sure but works for me without this
            data: formData,
            contentType: false, //this is requireded please see answers above
            processData: false, //this is requireded please see answers above
            //cache: false, //not sure but works for me without this
            error   : ErrorHandler,
            success : successHandler
        });
    }
});

this will than correctly populate your MVC model, please make sure in your Model, The Property for HttpPostedFileBase[] has the same name as the Name of the input control in html ie 这将正确填充您的MVC模型,请确保在模型中,HttpPostedFileBase []的属性与html中输入控件的名称相同,即

<input id="fileupload" type="file" name="UploadedFiles" multiple>

public class MyViewModel
{
    public HttpPostedFileBase[] UploadedFiles { get; set; }
}

#6楼

For me following code work 对我来说,下面的代码工作

$(function () {
    debugger;
    document.getElementById("FormId").addEventListener("submit", function (e) {
        debugger;
        if (ValidDateFrom()) { // Check Validation 
            var form = e.target;
            if (form.getAttribute("enctype") === "multipart/form-data") {
                debugger;
                if (form.dataset.ajax) {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    var xhr = new XMLHttpRequest();
                    xhr.open(form.method, form.action);
                    xhr.onreadystatechange = function (result) {
                        debugger;
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            debugger;
                            var responseData = JSON.parse(xhr.responseText);
                            SuccessMethod(responseData); // Redirect to your Success method 
                        }
                    };
                    xhr.send(new FormData(form));
                }
            }
        }
    }, true);
});

In your Action Post Method, pass parameter as HttpPostedFileBase UploadFile and make sure your file input has same as mentioned in your parameter of the Action Method. 在您的Action Post方法中,将参数作为HttpPostedFileBase UploadFile传递,并确保您的文件输入与Action Method参数中提到的相同。 It should work with AJAX Begin form as well. 它也应该与AJAX Begin表单一起使用。

Remember over here that your AJAX BEGIN Form will not work over here since you make your post call defined in the code mentioned above and you can reference your method in the code as per the Requirement 在此记住,由于您在上述代码中定义了post调用,因此您的AJAX BEGIN表单将无法在此处使用,并且您可以根据要求在代码中引用您的方法

I know I am answering late but this is what worked for me 我知道我回答晚了,但这对我有用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值