從文件場
做的第一件事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:
- 過程數據 - 因爲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.處理窗體提交
上傳功能的成功方法傳遞從服務器發送回提交函數的數據。然後,您可以傳遞到服務器。您的文章的一部分:
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
你試過 [**此插件**](HTTP://放棄.ie/notebook/simple-file-uploads-using-jquery-ajax) 。我已經使用過2次,或者可能會使用3次,但它的作用就像魅力。 – CodeMonk
我使用plUpload插件。似乎是一個更受歡迎的,它對我來說很好。 http://www.plupload.com/ – johnnyarguelles
謝謝你們,CodeMonk是的,我試過使用這個代碼,這幾乎是問題中的代碼。和約翰尼謝謝你,但我試圖解決這個問題,我不想使用插件。 – user3195129