![](/img/trans.png)
[英]How to send multipart/form-data to server using Ajax, PHP and jQuery?
[英]Using jQuery to send data from a multipart/form-data through ajax
我現在已經整天都在工作,但是我無法使其正常工作。
我基本上使用jQuery庫收到了一個簡單的Ajax請求,我想通過mutlipart / form-data文件輸入發送我發布的數據,但是,我已經嘗試了所有可以想到的方法。
我的文件上傳腳本已經准備就緒,正在等待文件名作為參數(也嘗試不使用),但是它只是不想從文件輸入框本身獲取數據。
有人可以啟發我如何在沒有其他插件的情況下執行此操作(多次上傳等)。
這是我的jQuery代碼:
函數uploadTimesheets(){
$('#waiting').show();
var error = '';
var msg = '';
//Performs the Ajax Request
var data = $.ajax({
type : 'POST',
url : '/ajax/timesheet/uploadNewTimesheets.php',
dataType : 'json',
contentType : 'multipart/form-data',
data : data,
error : error,
msg : msg,
success : function(data){
if(!data){
$('#notification').removeClass(this).addClass('notification-success').html(data).show().delay(1200).fadeOut(800);
getActiveTimesheets(getSelectedPage());
}else{
$('#notification').removeClass().addClass('notification-error').html(data.msg + data.errorList).show();
alert('PHHAIL');
}
$('#waiting').hide();
function(xhr, status, errorThrown){
$('#waiting').hide();
}
}
});
}
這是我的PHP上傳腳本:
/**
* Creates a directory in the active directory with the given folder name
*
* @author RichardC
* @param string $dirName
* @return boolean
*/
public function createDir( $dirName ) {
$docRoot = getenv('DOCUMENT_ROOT');
if (!is_dir(sprintf('%s/%s', $docRoot, $dirName))) {
$makeDir = mkdir(sprintf('%s/%s', $docRoot, $dirName));
echo sprintf('Creating a folder called \'/%s/\' ...', $dirName);
if ($makeDir) {
echo '<br />Successfully created the folder.<br />';
return true;
} else {
echo sprintf('<br /> Sorry, please create the folder manually at: %s/%s', $docRoot, $dirName);
return false;
}
}
}
/**
* Uploads either a CSV or an EXCEL file to a temporary directory
*
* @author RichardC
* @param Resource $file
* @return Boolean true/false
*/
public function upload( $filename ) {
$filename = (!isset($filename)) ? $this->file : $filename;
//Get the document root
$docRoot = getenv('DOCUMENT_ROOT');
$this->createDir('uploads');
if (($_FILES['file']['type'] == 'application/vnd.ms-excel') || ($_FILES['file']['type'] == 'application/csv') || ($_FILES['file']['type'] == 'text/csv') || ($_FILES['file']['type'] == 'text/comma-separated-values') || ($_FILES['file']['type'] == 'application/excel') &&
($_FILES["file"]["size"] < 1000000)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
if (file_exists($docRoot . "upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
$this->file = $docRoot . '/upload/' . $_FILES["file"]["name"];
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], $docRoot . "/upload/" . $_FILES["file"]["name"]);
$this->file = $docRoot . '/upload/' . $_FILES["file"]["name"];
}
}
} else {
echo "Invalid file";
return false;
}
//Remove the unwanted file now
$this->fileContents = file_get_contents($this->file);
@unlink($this->file);
unset($this->file);
return true;
}
如果有人可以提供幫助,將不勝感激!
為了使您的multipart / formdata工作,您必須在ajax請求中添加一些額外的東西:
cache: false,
contentType: false,
processData: false,
您可以通過執行以下操作輕松創建數據字段:
var uploadData = $("#uploadFile").prop("files")[0];
var newData = new FormData();
$.each($('#uploadFile').prop("files"), function(i, file) {
newData.append('file-'+i, file);
});
在您的ajax請求中,您必須設置以下內容:
data: newData
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.