上传文件和数据使用Ajax PHP FORMDATA提交XHR
这位朋友你好我试图在一段时间内通过AJAX这种形式上传数据和文件:上传文件和数据使用Ajax PHP FORMDATA提交XHR
<form id="formarea" class="form-horizontal" name="desk">
<input type="text" class="form-control " name="i_txt_2">
<input type="number" class="form-control " name="i_txt_3" required>
<input type="file" name='i_files_1'>
<input type="file" name='i_files_2'>
<input type="file" name='i_files_3'>
</form>
阿贾克斯:
$('[id^="save"]').on("click", function (event, xhr, settings) {
var id = event.target.id;
var name = $("#formarea").attr("name");
$.ajax({
type:"POST",url:"index.php",data:$("#formarea").serialize()+ '&idprocess=' + id + '&idform=' + name,
error: function(xhr,status,error){console.log(error)},
success: function(response) {
$("#areasmg").html(response);
$("#MsgArea").removeClass("").addClass("alert alert-warning alert-dismissable");
$("#MsgArea").show();
}
});
});
问题: 在请求我没有收到在服务器端的PHP序列化的输入文件:i_files_1 我怎样才能连接到数据发送:
data:$("#formarea").serialize()+ '&idprocess=' + id + '&idform=' + name + '&Files' + files[]Serialized ,
UPDATE问题就迎刃而解了:
//If you have button to submit Form
$('[id^="BTN-"]').on("click", function (event, xhr, settings) {
var id = event.target.id; //get id buton to filter if you like get control over the button clicked
var req = 0;
$('#formarea *').filter(':input').each(function(){ //filter all requiered input field
if($(this).val() === "" && $(this).attr('required')){req ++;}
});
if(req == 0){
var name = $("#formarea").attr("name"); //get name of form if you like get control over the form submited
//window.WindowsWait();
var input1 = $("<input>").attr("type", "hidden").attr("name", "idprocess").val(id); //Adding field for more controls if you neet handle from PHP
var input2 = $("<input>").attr("type", "hidden").attr("name", "idform").val(name); //Adding field for more controls if you neet handle from PHP
$('#formarea').append($(input1)); //inserting on Html
$('#formarea').append($(input2)); //inserting on Html
event.preventDefault(); //prevent default submit
//get form an serialize data with FormData
var $form = $("#formarea"),
formData = new FormData(),
params = $form.serializeArray();
var inputs = $("input[type=file]");
//Get all Input tipe Files
$.each(inputs, function (obj, v) {
// Prefix the name of uploaded files with "uploadedFiles-"
// Of course, you can change it to any string
var file = v.files[0];
var name = $(v).attr("name");//you can work with the name
formData.append(name, file);
});
// Add all params to the formData
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
//performing the submit
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
error: function(xhr,status,error){console.log(error)},
success: function(response) {
alert(response);//print response server
}
});
}else{
alert("Error: You must fill all field, there " + req + " Empty Fields.");//handle Error Empty Fields
}
});
测试:
的print_r($ _ FILES);
UPDATE问题就迎刃而解了:
//If you have button to submit Form
$('[id^="BTN-"]').on("click", function (event, xhr, settings) {
var id = event.target.id; //get id buton to filter if you like get control over the button clicked
var req = 0;
$('#formarea *').filter(':input').each(function(){ //filter all requiered input field
if($(this).val() === "" && $(this).attr('required')){req ++;}
});
if(req == 0){
var name = $("#formarea").attr("name"); //get name of form if you like get control over the form submited
//window.WindowsWait();
var input1 = $("<input>").attr("type", "hidden").attr("name", "idprocess").val(id); //Adding field for more controls if you neet handle from PHP
var input2 = $("<input>").attr("type", "hidden").attr("name", "idform").val(name); //Adding field for more controls if you neet handle from PHP
$('#formarea').append($(input1)); //inserting on Html
$('#formarea').append($(input2)); //inserting on Html
event.preventDefault(); //prevent default submit
//get form an serialize data with FormData
var $form = $("#formarea"),
formData = new FormData(),
params = $form.serializeArray();
var inputs = $("input[type=file]");
//Get all Input tipe Files
$.each(inputs, function (obj, v) {
// Prefix the name of uploaded files with "uploadedFiles-"
// Of course, you can change it to any string
var file = v.files[0];
var name = $(v).attr("name");//you can work with the name
formData.append(name, file);
});
// Add all params to the formData
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
//performing the submit
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
error: function(xhr,status,error){console.log(error)},
success: function(response) {
alert(response);//print response server
}
});
}else{
alert("Error: You must fill all field, there " + req + " Empty Fields.");//handle Error Empty Fields
}
});
在谷歌一点点搜索应该给你一个优秀的教程由Mozilla
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
然后你忘记添加到您的表单标签:enctype="multipart/form-data"
接受文件上传。
的支持,这不起作用,因为它是一种其他输入类型的文本= text/number –
您总是可以混合输入类型!在服务器端,您只需使用$ _FILES超级全局和其他输入来处理具有$ _POST超级全局的文件。 –
好的,我需要更新脚本,但它在铬上工作? –
我不能写/在这里发布的所有信息的空间,想要的,但你可以去http://moriche.ch/walter下载一个完整的工作解决方案......
没有头指令文件仍然会很好地工作。下面是该文件的内容:
<?php
// file-processor.php
// HEADER HAS BEEN REMOVED, YET IT WILL STILL WORK...
// HERE YOU CAN ACCESS ALL THE FIELDS THAT ARE CONTAINED IN THE FORM.
// EVERY ONE OF THEM: FROM NUMBER FIELD TO TEXT AREA, ETC ;-)
$text2 = isset($_POST['text2']) ? htmlspecialchars(trim($_POST['text2'])) : null;
$text3 = isset($_POST['text3']) ? htmlspecialchars(trim($_POST['text3'])) : null;
$arrStatus = array();
$arrResponse = array();
if(isset($_FILES['i_files_1'])){
$fileData = $_FILES['i_files_1'];
$arrStatus["i_files_1"] = uploadFile($fileData);
}
if(isset($_FILES['i_files_2'])){
$fileData = $_FILES['i_files_2'];
$arrStatus["i_files_2"] = uploadFile($fileData);
}
if(isset($_FILES['i_files_3'])){
$fileData = $_FILES['i_files_3'];
$arrStatus["i_files_3"] = uploadFile($fileData);
}
function uploadFile($fileData, $uploadDir = __DIR__ . "/img"){
$flTName = $fileData['tmp_name'];
$flName = $fileData['name'];
$flType = $fileData['type'];
$flSize = $fileData['size'];
$flErr = $fileData['error'];
$info = new SplFileInfo($flName);
$ext = $info->getExtension();
if(!is_dir($uploadDir)){
mkdir($uploadDir, 0777, true);
}
$pixDst = $uploadDir . "/uploaded_pix_" . generateRandomString() . "." . $ext;
return move_uploaded_file($flTName, $pixDst);
}
foreach($arrStatus as $fileKey=>$boolStatus){
if($boolStatus){
$arrResponse[$fileKey] = $fileKey . " was successfully uploaded...";
}else{
$arrResponse[$fileKey] = "Error: could not upload \"{$fileKey}\"";
}
}
function generateRandomString($length = 8) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
die(json_encode($arrResponse));
JAVASCRIPT
(function ($) {
$(document).ready(function(e) {
var text2 = $("input[name=i_txt_2]");
var text3 = $("input[name=i_txt_3]");
var files = $("input[type=file]");
var theForm = $("#formarea");
var formAction = theForm.attr("action");
files.each(function(dt, dom){
var target = $(this);
target.change(function(evt) {
evt.preventDefault();
var dis = $(this);
var dis_val = dis.val();
// HERE YOU CAN JUST ADD THE FILE TYPES YOU WANT TO SUPPORT
// LIKE MP3, MP4, PDF, ETC...
if (dis_val && /(\.)(jpg|jpeg|png|gif|bmp)$/.test(dis_val)) {
// THE RIGHT FILES WERE UPLOADED SO DO NOTHING;
} else {
alert("Only Images in with the Format: (JPG, JPEG, PNG, GIF, BMP) are allowed.");
dis.val(null);
return false;
}
});
});
theForm.submit(function (evt) {
var $this = $(this);
evt.preventDefault();
$this.attr("action", formAction).ajaxSubmit({
dataType: "HTML",
success: confirmFileUpload,
cache: false
});
});
function confirmFileUpload(data){
console.log(data);
console.log("File was uploaded and the World is fine again...");
}
});
})(jQuery);
谢谢你这个例子,这是一个很好的帮助,但问题是这个脚本是通用的,并且用于多次维护屏幕,例如在#formarea(表单)内可以有很多输入文本/ num/date/ETC,并且需要动态捕获而不是静态的。文件是JPG,PDF格式,excel,powerpoint,只有一个输入,但可以有多种输入形式 –
@WalterNuñez当然......但所有这些输入字段也会发布...即使您有100个输入字段,都发布了,你可以像访问php中发布的任何数据一样访问它们。在PHP文件里面;简单地做$ _POST ['field_name'],你有价值...你可以试试它,如果你愿意...... ;-) – Poiz
好吧,你可以帮我避免标题('Content-type:应用/ JSON');从客户端和服务器端becouse我有很多没有JSON编码的响应,并需要保持这种兼容性。 –
$ _FILES检查文件的输入,同时$ _ POST把手文字和其他输入类型 –
我有几个问题,但首先,为什么'$(“#formarea”)。serialize()+'&id process ='+ id +'&idform ='+ name'?使这些参数成为实际表单的一部分,您尝试添加。 –
你也需要使用FormData对象上传AJAX的文件 – Musa