如何使用formdata方法将Angular2表单(以及图像)中的数据提交给PHP?

时间:2018-04-11 13:20:04

标签: php angular angular2-forms

表单有文本输入和文件输入。我从here学习了教程。

这是我的 add.component.ts 文件: -

import { AdminPage } from '../../../_models/admin.page.model';
import { AdminPageService } from '../../../_admin_service/admin.page';
import { ImageUploadService } from '../../../_common_service/image.upload';


export class AddComponent implements OnInit, AfterViewInit {
    .............
    .............

    adminPageModel = new AdminPage('', '', '', '','');  

    constructor(private route: ActivatedRoute,
        private router: Router,
        private _adminPage: AdminPageService,
        private _imageUpload: ImageUploadService,
        fb: FormBuilder,
        private _flashMessagesService: FlashMessagesService) { 
            this.addPageFormGroup = fb.group({
              'title' : [null, Validators.compose([Validators.required])],
              'meta_keyword': [null, Validators.required],
              'meta_description': [null, Validators.required],
              'image':[],
              'desc': [null, Validators.required]
            });
    }


    formImageUpload(event){
        this._imageUpload.onFileChange(event,this.addPageFormGroup);
    }

    submitAddPage(value:any){    
        this.addPageFormGroup.get('desc').setValue($('.Editor-editor').html());
        const adminPageModule = this._imageUpload.prepareSave(this.addPageFormGroup);
        this._adminPage.postAdminPageAdd(adminPageModule).subscribe(
          data => {
                this.responseStatus = data;
                if(this.responseStatus.status == 1)
                {
                  this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 2000 });
                }
                else
                {
                  this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-danger', timeout: 2000 });
                }
              },
          err => {
                console.log(err)
              },
          () => {}
        ); 
      this.status = true;       
    }
}

这是 image.upload.ts 服务文件,我们从表单中设置formdata: -

@Injectable()
export class ImageUploadService {
    constructor() {}

    onFileChange(event, formHasImage:any) {
        if(event.target.files.length > 0) {
            let file = event.target.files[0];
            formHasImage.get('image').setValue(file);
        }
    }

    prepareSave(formHasImage): any {
        let input = new FormData();
        input.append('image', formHasImage.get('image').value);
        input.append('title', formHasImage.get('title').value);
        input.append('desc', formHasImage.get('desc').value);
        input.append('meta_keyword', formHasImage.get('meta_keyword').value);
        input.append('meta_description', formHasImage.get('meta_description').value);
        console.log(input);
        return input;
    }
}

这是我们正在使用API​​的 admin.page.ts 服务文件。这是通过参考这个答案here来完成的。

@Injectable()
export class AdminPageService {
    http : Http;
    actionUrl : string;
    admin_page_add_url: string;
    postAdminPageAddData: AdminPage;
    adminPageAddResponse:Object= []; 


    constructor(public _http: Http) {
       this.http = _http;
       this.admin_page_add_url = 'http://localhost/angproject/phpscript/adminpage2.php';
    }

    // The form Data is being sent as parameter
    postAdminPageAdd(postAdminPageAddFormData: any) {   
        let headers = new Headers();
        headers.append('enctype', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        this.actionUrl = this.admin_page_add_url;
        return this.http.post(this.actionUrl, 
                                    { postAdminPageAddFormData },
                                    { headers: headers })
                                .map(res => res.json()).share();
    }
}

这是我们发送数据的服务器端php文件。这是根据接受的答案here进行的: -

<?php
error_reporting(E_ALL);
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Access-Control-Allow-Headers: Content-Type, enctype");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header('Content-Type: application/json; charset=utf-8');
header('enctype: multipart/form-data');

include('connection.php');
$error = array();

if(isset($_FILES['image']))
{
    $image = 'Image Exists';
}
else
{
    $error[] = "Image was not entered";
    $image = '';
}

if(isset($_POST['title']) && !empty($_POST['title']))
    $title = $_POST['title'];
else 
    $error[] = "Title was not entered";


if(empty($error))
{
    $response['status'] = 1;
    $response['message'] = $image;
    $response['error'] = $conn->error;
}
else
{
    $response['status'] = 0;
    $response['message'] = "Parameter missing";
    $response['error'] = $error;
}
$respond = json_encode($response);
echo $respond;
exit;
?>

我的问题是,我总是得到这个json的回应: -

{
  "status": 0,
  "message": "Parameter missing",
  "error": [
    "Image was not entered",
    "Title was not entered"
  ]
}

似乎formdata没有被发送到服务器端。我在这做错了什么?记住它,我也有其他过程,提交表格。但在这种情况下,我可以通过不使用formdata成功地将数据发送到服务器,因此,我无法在该方法中实现文件上传。

注意:当我console.log(input)时,我明白了: -

enter image description here

2 个答案:

答案 0 :(得分:1)

您的AdminPageService的postAdminPageAdd方法存在两个问题。 首先,Headers.append()不会改变Headers对象,它会返回一个带有原始头和新头的新Headers对象。所以你需要做一些事情:

let headers = new Headers();
headers = headers.append('enctype', 'multipart/form-data');
headers = headers.append('Accept', 'application/json');

其次,帖子中的FormData对象不应该用大括号括起来 - 如果你这样做,它应该有效:

return this.http.post(
   this.actionUrl, 
   postAdminPageAddFormData, 
   { headers: headers }
).map(res => res.json()).share();

答案 1 :(得分:0)

尝试将文件直接附加到FormData对象。

@Injectable()
export class ImageUploadService {
file: File;
constructor() {}

onFileChange(event, formHasImage:any) {
    if(event.target.files.length > 0) {
        file = event.target.files[0];
    }
}

prepareSave(formHasImage): any {
    let input = new FormData();
    input.append('image', this.file);
    input.append('title', formHasImage.get('title').value);
    input.append('desc', formHasImage.get('desc').value);
    input.append('meta_keyword', formHasImage.get('meta_keyword').value);
    input.append('meta_description', formHasImage.get('meta_description').value);
    console.log(input);
    return input;
    }
}