douwei8911 2018-04-11 13:20
浏览 144
已采纳

如何使用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 2018-04-11 13:35
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)