[英]Send image file from angular to php
I'm trying to send image that choose from angular app to my php here is what i do. 我正在尝试将从角度应用程序选择的图像发送到我的PHP,这是我的工作。
onSubmit(e) {
e.preventDefault();
this.submitted = true;
if (this.profilForm.invalid) {
return;
}
this.email = this.profilForm.controls['email_txt'].value;
this.fullname = this.profilForm.controls['fullname_txt'].value;
this.address = this.profilForm.controls['address_txt'].value;
this.telp = this.profilForm.controls['telp_txt'].value;
this.profilapi.updateProfil( this.fullname, this.address , this.telp , this.email, this.selectedFile ).subscribe((data: Array<object>) => {
this.userinfo = data;
console.log( "blablabla - " + this.userinfo);
this.alertService.danger("Something wrong please try again later");
},
error => {
console.log( "err - " + error );
this.alertService.danger("Something error, please try again later");
}
);
}
onFileChanged(event) {
this.selectedFile = event.target.files[0]
}
my service 我的服务
updateProfil(fullname,address,telp,email,profil){
return this.httpClient.post(
`${this.API_URL}` ,
{
"fullname" : fullname,
"address" : address ,
"telp" : telp ,
"email" : email ,
"profil" : profil
}
);
}
ini here is my php so far. 到目前为止,这是我的PHP。
<?php
include_once("Crud.php");
$crud = new Crud();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$postdata = file_get_contents("php://input");
$request = json_encode($postdata);
$email = $request->email;
$fullname = $request->fullname;
$address = $request->address;
$phone = $request->phone;
echo $email;
?>
how can i receive the image at my php and upload it to specified folder ? 我如何在php中接收图像并将其上传到指定的文件夹? thanks in advance and sorry for my english. 在此先感谢,对不起我的英语。
You are trying to get file data via php://input
but documentation warning us that this way is not avaliable for enctype="multipart/form-data"
forms, so you have to use $_POST
array. 您正在尝试通过php://input
获取文件数据,但文档警告我们,这种方法不适用于enctype="multipart/form-data"
表单,因此必须使用$_POST
数组。
Also if you send POST request to PHP script, all uploaded files do not placed into $_POST
array, they are placed into the $_FILES
array and than you have to move them with yourself: 另外,如果您将POST请求发送到PHP脚本,则所有上传的文件都不会放入$_POST
数组中,而是将它们放入$_FILES
数组中,然后您必须自己移动它们:
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
More info here: http://php.net/manual/en/features.file-upload.php 此处提供更多信息: http : //php.net/manual/zh/features.file-upload.php
This is how I upload files from Angular
to PHP
: (This is not the optimal solution but it works just fine) 这是我将文件从Angular
上传到PHP
:( 这不是最佳解决方案,但效果很好)
1- Read the file from the input and put it in json object: 1-从输入中读取文件并将其放在json对象中:
readFile(event){
let reader = new FileReader();
if(event.target.files && event.target.files.length > 0) {
let file:File = event.target.files[0];
reader.readAsDataURL(file);
reader.onload = () => {
let fielToUpload = {
fileName: file.name,
fileType: file.type,
fileExtension: file.name.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);,
value: reader.result.split(',')[1]
};
this.profilapi.updateProfil(fielToUpload).subscribe(res => // do whatever you want here);
};
}
}
2- In your service 2-为您服务
updateProfil(fielToUpload: any): Observable<any>{
let _headers = new HttpHeaders({
'Content-Type': 'application/json',
});
return this._http.post('path/to/your/api', fielToUpload, {headers: _headers})
}
3- Read the object from your php file: 3-从您的php文件中读取对象:
$postdata = file_get_contents("php://input");
$data = json_encode($postdata);
$fileName = time().'.'.$data['fileExtension'];
$path = '/path/to/upload/directory/'.$fileName;
file_put_contents($path, base64_decode($data['value']));
If you want send image or file with data you must use FormaData object for example : 如果要发送带有数据的图像或文件,则必须使用FormaData对象 ,例如:
public postFile(data: any) { const endpoint ='url' const formData: FormData = new FormData(); formData.append('image', data.file, data.file.name); formData.append('type', data.type); formData.append('label', data.label); formData.append('profile', data.label); let headers = new HttpHeaders(); headers = headers.set('Content-Type', 'multipart/form-data'); headers = headers.set('Accept', 'application/json'); return this._http .post(endpoint, formData, { headers: headers }) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.