【问题标题】:Send cordova FileTransfer parameters to php server using ionic 2/3使用 ionic 2/3 将 cordova FileTransfer 参数发送到 php 服务器
【发布时间】:2019-02-13 19:55:24
【问题描述】:

我有一个包含一些字段的表单,并且还使用相机插件将 ionic 2/3 的图片上传到 php 服务器。所以我想将带有上传图片的表单数据发送到服务器。以下是我的代码:

添加事件.html

<form (ngSubmit)="add_event()" #eventForm="ngForm">
<ion-item>
    <ion-label fixed>Title</ion-label>
    <ion-input placeholder="Title here"
       name="title" [(ngModel)]="eventData.title" required>
    </ion-input>
  </ion-item>

   <ion-item>
    <ion-label>Select Photo</ion-label>
    <ion-icon name="camera" (click)="presentActionSheet()" item-right></ion-icon>
   </ion-item>
    <img src="{{pathForImage(lastImage)}}" style="width: 100%" [hidden]="lastImage === null">
    <h5 align="center" [hidden]="lastImage !== null" class="preview_text">Photo Preview</h5>

<button ion-button full [disabled]="eventForm.invalid">Add Event</button>
</form>

添加事件.ts

filename: string;
eventData = { title: '', image: this.filename};

public add_event() {
// Destination URL
var url = apiURL.BASE_URL+"add_events";

// File for Upload
var targetPath = this.pathForImage(this.lastImage);

 // File name only
 var filename = this.lastImage;

var options = {
fileKey: "file",
fileName: filename,
chunkedMode: true,
mimeType: "multipart/form-data",
params : this.eventData // Is this where i pass parameters to php?
};

const fileTransfer: FileTransferObject = this.transfer.create();

  this.loading = this.loadingCtrl.create({
    content: 'Submitting...',
  });
  this.loading.present();

 // Use the FileTransfer to upload the image
    fileTransfer.upload(targetPath, url, options).then(data => {
      this.loading.dismissAll()
      this.presentToast('Event succesfully added.');
      console.log(data);
      console.log(options);
      console.log(this.eventData);
    }, err => {
      this.loading.dismissAll()
      this.presentToast('Error while uploading event.');
      console.log(err);
    });

}

add.php(使用 Slim 框架)

 $data = json_decode($request->getBody());

$title=$data->title; //returns null
$image=$data->image; //returns null

header('Access-Control-Allow-Origin: *');

// for image upload
$file_name = $_FILES["file"]["name"];
$tmp = $_FILES["file"]["tmp_name"];

$target_path = "../path/to/picfolder";

$target_path = $target_path . basename( $file_name );

现在的问题是,当我提交表单时,php 端没有收到标题和图像参数。如何在应用提交时成功传递参数?

【问题讨论】:

    标签: php typescript ionic2 ionic3 slim


    【解决方案1】:

    由于您以原始 JSON 格式发送参数,因此这是在服务器端检索数据的方法:(只需将您的第一行替换为此)

    json_decode(file_get_contents('php://input'), true);

    【讨论】:

    • 它不工作。我传递参数的方式是否正确?还是我解码 JSON 对象的方式?
    • print_r(json_decode(file_get_contents('php://input'), true)); 可以试试输出数据吗?
    • 终于搞定了。必须使用 $_POST['title'] 而不是 $data->title。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2018-08-31
    • 2020-07-04
    • 1970-01-01
    相关资源
    最近更新 更多