A.从文件字段抓取文件数据
首先要做的是将一个函数绑定到文件字段上的更改事件和一个用于抓取文件数据的函数:
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
这会将文件数据保存到文件变量中以供以后使用。
B.在提交时处理文件上传
提交表单时,您需要在其自己的 AJAX 请求中处理文件上传。添加如下绑定和函数:
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
这个函数的作用是创建一个新的 formData 对象并将每个文件附加到它上面。然后它将该数据作为请求传递给服务器。 2个属性需要设置为false:
- processData - 因为 jQuery 会将文件数组转换为
字符串,服务器无法获取。
- contentType - 将此设置为 false,因为 jQuery 默认为 application/x-www-form-urlencoded 并且不发送文件。还将其设置为 multipart/form-data
似乎也不起作用。
C.上传文件
快速而肮脏的 php 脚本来上传文件并传回一些信息:
<?php // You need to add server side validation and better error handling here
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = './uploads/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
IMP:不要用这个,自己写吧。
D.处理表单提交
upload函数的success方法将服务器发回的数据传递给submit函数。然后,您可以将其作为帖子的一部分传递给服务器:
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
最后说明
此脚本只是一个示例,您需要处理服务器端和客户端验证,并以某种方式通知用户文件上传正在发生。我在Github 上为它创建了一个项目,如果你想看到它的工作。
Referenced From