Javascript 通过ajax post将文件与表单数据一起发送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33761469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:27:03  来源:igfitidea点击:

Sending file together with form data via ajax post

javascriptphpjqueryajaxfile-upload

提问by Akshay

I'm trying to upload a file via ajax together with some fields in a form. However, it doesn't work. I get this error.

我正在尝试通过 ajax 上传文件以及表单中的一些字段。但是,它不起作用。我收到这个错误。

Undefined Index :- File

未定义索引:- 文件

Here's my code.

这是我的代码。

HTML

HTML

    <!-- File Button --> 
    <div class="form-group">
    <label class="col-md-4 control-label" for="file">Upload Software / File</label>
    <div class="col-md-4">
    <input id="file" name="file" class="input-file" type="file">
    </div>
    </div>

<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>  
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required=""> 
</div>
</div>

Ajax

阿贾克斯

$("#add_product").click(function(e){
    e.preventDefault();
    product_name = $("product_name").val();
    //d = $("#add_new_product").serialize();
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: $("#add_new_product").serialize(),
        success: function(response)
        {
            //
            alert(response);

        }
    })
});

PHP

PHP

if (0 < $_FILES['file']['error']) 
{
 echo ":!";
}
else 
{
echo "ASa";
}

What am I missing here?

我在这里缺少什么?

采纳答案by Praveen Kumar Purushothaman

Can you try using FormData():

你可以尝试使用FormData()

$("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;
});

The above is a sample code, but you may use it to modify it.

以上是示例代码,但您可以使用它来修改它。

回答by Suhail Keyjani

you can use FormData

你可以使用 FormData

$("#add_product").click(function(e){
    e.preventDefault();
    var fdata = new FormData()
    
   fdata.append("product_name",$("product_name").val());
  
    if($("#file")[0].files.length>0)
       fdata.append("file",$("#file")[0].files[0])
    //d = $("#add_new_product").serialize();
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data:fdata,
        contentType: false,
        processData: false, 
        success: function(response)
        {
            //
            alert(response);

        }
    })
});
 <!-- File Button --> 
    <div class="form-group">
    <label class="col-md-4 control-label" for="file">Upload Software / File</label>
    <div class="col-md-4">
    <input id="file" name="file" class="input-file" type="file">
    </div>
    </div>

<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>  
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required=""> 
</div>
</div>

回答by vibs2006

We need to acknowledge first is that we need to APPEND both Form Input Data and Form File(s) into a single FormDatavariable.

我们首先需要承认的是,我们需要将表单输入数据和表单文件都附加到单个 FormData变量中。

Here is my solution in which I have enabled Multi Fileoption so that this solution can fit for all examples.

这是我的解决方案,其中我启用了多文件选项,以便此解决方案适用于所有示例。

It is Importantto include nameattribute in the input controls to make it work properly on server side in most of cases. If you are using C# then you can use simply Request.Form["nameAttribute"]to simply get the function. It is similar for Java and other languages.

在大多数情况下,在输入控件中包含name属性以使其在服务器端正常工作很重要。如果您使用的是 C#,那么您可以简单地使用Request.Form["nameAttribute"]来简单地获取该函数。Java 和其他语言的情况类似。

My Sample Code is

我的示例代码是

   $(document).ready(function () //Setting up on Document to Ready Function
    {
        $("#btnUpload").click(function (event) {

            //getting form into Jquery Wrapper Instance to enable JQuery Functions on form                    
            var form = $("#myForm1");

            //Serializing all For Input Values (not files!) in an Array Collection so that we can iterate this collection later.
            var params = form.serializeArray();

            //Getting Files Collection
            var files = $("#File1")[0].files;

            //Declaring new Form Data Instance  
            var formData = new FormData();

            //Looping through uploaded files collection in case there is a Multi File Upload. This also works for single i.e simply remove MULTIPLE attribute from file control in HTML.  
            for (var i = 0; i < files.length; i++) {
                formData.append(files[i].name, files[i]);
            }
            //Now Looping the parameters for all form input fields and assigning them as Name Value pairs. 
            $(params).each(function (index, element) {
                formData.append(element.name, element.value);
            });

            //disabling Submit Button so that user cannot press Submit Multiple times
            var btn = $(this);
            btn.val("Uploading...");
            btn.prop("disabled", true);

            $.ajax({
                url: "Handler.ashx", //You can replace this with MVC/WebAPI/PHP/Java etc
                method: "post",
                data: formData,
                contentType: false,
                processData: false,
                success: function () {
                    //Firing event if File Upload is completed!  
                    alert("Upload Completed");
                    btn.prop("disabled", false);
                    btn.val("Submit");
                    $("#File1").val("");

                },
                error: function (error) { alert("Error"); }

            });

        });

    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post" id="myForm1">
    <p><textarea id="TextArea1" rows="2" cols="20" name="TextArea1"></textarea></p>
    <p><input id="File1" type="file" multiple="multiple" /></p>
    <input id="btnUpload" type="button" value="Submit" />
    </form>

For a working example (asp.net C# with handlers) you can visit sample code on https://github.com/vibs2006/HttpFileHandlerFormDataSample

对于工作示例(带有处理程序的 asp.net C#),您可以访问https://github.com/vibs2006/HttpFileHandlerFormDataSample 上的示例代码