2
我有一個使用A2 CLI的項目,並且我嘗試使用類型爲「file」的輸入標籤上傳文件。我的東西在整個工作流程中發揮作用,但是我無法從客戶端到服務器獲取文件數據。Angular 2 http.post FormData()向PHP上傳文件
我有下面的代碼在打字稿:
myFnc(event){
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
console.log(file);
console.log(file.name);
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
/*
this was the culprit:
headers.append('Content-Type', 'multipart/form-data');
worked for me by changing it to:
*/
headers.append('enctype', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
console.log(formData);
console.log(options);
this.http.post('./assets/data/upload-persona-document.service.php', formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data =>{
console.log(data);
},
error =>{
console.log(error);
}
)
}
}
我沒有得到任何錯誤,讓我檢查在控制檯的結果。 (我知道console.log(formData)實際上不會輸出formData的內容,我試過.entries(),但是我已經讀過FormData方法在TS中不被很好的支持)。
在upload-人物-document.service.php:
<?php
$target_dir = "../docs/Personas/";
$json = array();
$postData = file_get_contents("php://input");
$input = json_decode($postData);
$json['input'] = $input;
$json['post'] = ($_POST);
$json['files'] = $_FILES;
$target_file = $target_dir . basename($_FILES["uploadFile"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
echo json_encode($json);
// ...a bunch of code that will act on the data when I can finally get it correctly...
當我返回響應,我得到:
[Log] {input: null, post: [], files: []} (main.bundle.js, line 1117)
我在我缺少什麼,我難住了。
您可以發佈您完全的.ts碼。 –