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

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

未定义的索引: – 文件

这是我的代码。

HTML

 

阿贾克斯

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

我在这里想念的是什么?

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

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

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

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

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

在大多数情况下,在输入控件中包含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 ie 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"); } }); }); });