我在这上面拔头发。
有什么方法可以解析Slim PHP中的表单数据,该数据会将数据放入数组中(就像JSON一样)。我可能会丢失一些东西,但是我尝试过的所有操作都将数据踢出了一个数组,而无法定位表单数据。任何帮助表示赞赏。
角组件(在表单提交时执行):
let memory: any = new FormData();
if (this.memory_images) {
for(var i = 0; i < this.memory_images.length; i++) {
memory.append('memory_images', this.memory_images[i], this.memory_images[i].name);
}
}
memory.append('memory_song', this.memory_song);
memory.append('memory_text', this.memory_text);
memory.append('memory_author', this.memory_author);
memory.append('memory_collection', this.memory_collection);
this.memoriesService.saveMemory(memory).subscribe(data => {
console.log(data);
// returns empty array
});
角记忆服务:
saveMemory(memory){
let headers = new Headers();
headers.append('Content-Type','multipart/form-data');
return this.http.post('http://{{ my api route }}/api/v1/memories', memory, {headers: headers})
.map(res => res);
}
Slim API路线:
$app->group(APIV1 . '/memories', function() {
$this->post('', function (Request $request, Response $response, $args) {
var_dump($request->getParsedBody());
return $response
});
});
该组件始终返回一个空数组。 有趣的是,当通过Postman提交表单数据时,返回的数据是数组中的一个字符串(我只发送了两个参数):
array(1) {
["------WebKitFormBoundaryXcRTrBhJge4N7IE2
Content-Disposition:_form-data;_name"]=>
string(181) ""memory_author"
Jack
------WebKitFormBoundaryXcRTrBhJge4N7IE2
Content-Disposition: form-data; name="memory_collection"
12345678
------WebKitFormBoundaryXcRTrBhJge4N7IE2--
"
}
该表格一直有效,直到我需要添加上传图片的功能为止。之前,我将表单输入收集到一个对象中,并以JSON的形式发送到API。我的理解是,由于现在需要附加文件,因此需要将提交作为表单数据发送。它是否正确?谢谢!!!
最佳答案
我在Angular和Slim API中也遇到了同样的问题,现在它的工作完全可以解决这些问题
1-不要在您的请求中从 Angular 代码发送任何 header
2-对于上传的照片,您将在Slim应用程序中获取上传的图像
在$ files数组中
这是一个将图像从 Angular 上传到Slim API的示例
在你的component.ts中
uploadimage(){
var formData = new FormData();
formData.append("image",this.image );
return this.http.post('http://Yourserver.com/UploadeFileAPI',formData)
.map(response =>response.json()).subscribe(
result=>{
console.log("image uploaded");
},
error=>{
console.log(error);
})}
在您的Slim应用中
$app->post('/uploadphoto',function ($req,$res){
$topic_name=$req->getParsedBodyParam('any parm name');
$files=$req->getUploadedFiles();
$newimage=$files['image'];}