【问题标题】:Sending file together with form data via ajax post通过ajax post发送文件和表单数据
【发布时间】:2016-02-19 02:11:40
【问题描述】:

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

未定义索引:- 文件

这是我的代码。

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

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

我在这里错过了什么?

【问题讨论】:

  • @M.Doye 这里的问题是,我有更多的数据和文件一起造成了麻烦。
  • 序列化函数不会在数据变量中包含文件有另一种机制来实现这一点,请谷歌它。
  • 您可以使用@M.Doye 解决方案,您必须在提交表单而不是文件更改事件时触发代码。
  • 看看这个,它完全符合您的要求。 stackoverflow.com/questions/10899384/…

标签: javascript php jquery ajax file-upload


【解决方案1】:

你可以试试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;
});

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

【讨论】:

  • 上述方法如何发送文件和数据
  • @annapoorani HTML 在问题中,而 jQuery 在答案中,应该可以。如果您遇到任何困难,请告诉我。
【解决方案2】:

你可以使用表单数据

$("#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>

【讨论】:

    【解决方案3】:

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

    这是我的解决方案,其中我启用了 Multi File 选项,以便该解决方案适用于所有示例。

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

    我的示例代码是

       $(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>

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

    【讨论】:

    • 运行代码 sn-p 给了我这个From an Embedded Page at stacksnippets.net Error。为什么?
    • @Tan 发生这种情况是因为像 'Handler.ashx' 这样的服务器端无法在 sn-p 下执行。为什么不使用我的 github 代码在本地主机上尝试相同的操作。
    • 你能分享你所指的github代码吗?我的意思是没有 ASP.NET/C# 的东西。
    • @Tan 它已经出现在我帖子的最后一行。 github.com/vibs2006/HttpFileHandlerFormDataSample
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 2020-09-03
    • 2018-03-08
    • 2021-03-30
    • 2017-06-22
    • 2016-03-11
    • 1970-01-01
    相关资源
    最近更新 更多