我想在Angular 9中通过http请求上传一个文件到php服务器,但是服务器无法接收到$_FILES中上传的文件。我写的代码有点像。
html:
<input type="file" (change)="detectFiles($event)" name="testFile" >
php:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
echo json_encode($_FILES['testFile']['name']);
?>
typescript:
detectFiles(event) {
const file = event.target.files[0];
this.httpClient.post<any>('http://localhost/test/uploadFile.php', file )
.subscribe( (response) => { console.log('uploading is done: ' + response); },
(error) => { console.log('ERR during the uploading: ' + error); }
);
}
当我上传一个文件时,结果出现了以下信息。ERR during the uploading: [object Object].有没有可能在服务器端从$_FILES中到达上传的文件呢,先谢谢了。
将你的文件添加到 Formdata
并将此
detectFiles(event) {
var formData = new FormData();
formData.append("file", event.target.files[0]);
this.httpClient.post<any>('http://localhost/test/uploadFile.php', formData)
.subscribe( (response) => { console.log('uploading is done: ' + response); },
(error) => { console.log('ERR during the uploading: ' + error); }
);
}