douwei8911
douwei8911
2018-04-11 13:20

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

已采纳

The form has text input and file-input. I studied the tutorial from here.

This is my add.component.ts file:-

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;       
    }
}

This is the image.upload.ts service file, where we are setting the formdata from the form:-

@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;
    }
}

This is the admin.page.ts service file where we are hitting the API. This is made by referring to this answer 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();
    }
}

This is the server side php file where we are sending the data. This is made on the accepted answer 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;
?>

My issue is, I am always getting this json response:-

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

It seems like the formdata aren't being sent to the server end. What am I doing wrong here? Mind it, I have other process too, to submit the form. But in that case, I can send data to server successfully by not using formdata and hence, I can't implement file-upload in that method.

Note: When I do console.log(input), I get this:-

enter image description here

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doupuchen6378 doupuchen6378 3年前

    You have two problems with your AdminPageService's postAdminPageAdd method. First, Headers.append() does not mutate the Headers object, it returns a new Headers object with the original headers and the new one. So you need to do something like:

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

    Second, the FormData object in the post should not be surrounded with curly brackets - it should work if you do:

    return this.http.post(
       this.actionUrl, 
       postAdminPageAddFormData, 
       { headers: headers }
    ).map(res => res.json()).share();
    
    点赞 评论 复制链接分享
  • douliangpo0128 douliangpo0128 3年前

    Try appending file directly to FormData object.

    @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;
        }
    }
    
    点赞 评论 复制链接分享