[英]Angular 2 http.post FormData() to PHP to upload a file
我有一個使用A2 CLI的項目,我正在嘗試使用type =“file”的輸入標簽上傳文件。 就整個工作流程而言,我的工作正常,但我無法從客戶端到服務器獲取文件數據。
我在TypeScript中有以下代碼:
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()但是我已經讀過TS中沒有很好地支持FormData方法。)
在upload-persona-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)
我對我所缺少的東西感到難過。
因此,經過一些挖掘和實驗后,我發現我必須在上面的headers.append()行中將Content-Type更改為enctype(更新該位。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.