【问题标题】:Upload file to server ionic and php将文件上传到服务器 ionic 和 php
【发布时间】:2019-11-18 00:57:25
【问题描述】:

我有将图像发送到我的服务器的代码,一切正常。但是我现在正在使用 ionic 中的输入标签将文件发送到我的服务器但是我似乎无法让它工作。

我从 php 文件中得到一个错误,说 undefined index 'file' HTML

<ion-col>
    <ion-label>Add a File</ion-label>
    <ion-input type='file' [(ngModel)]="fileName"></ion-input>
</ion-col>

TS 文件

addFile() {
    this.addService.addFile(this.fileName).subscribe(res => {
        console.log(res);
    });
}

服务

addFile(file) {
    let headers = new HttpHeaders();
    // headers = headers.set('Content-Type', 'application/json');
    headers = headers.set('Authorization', '' + this.token);
    const formData = new FormData();
    formData.append('file', file);
    return this.http.post<any>('http://domain.fileUpload.php', formData, {headers});
}

PHP API

$target_path = "files/";
$target_path = $target_path . basename( $_FILES['file']['name']);
$findDate = date("Y-m-d");

if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {             
    header('Content-type: application/json');
    $data = ['success' => true, 'message' => 'Upload and move success'];

    echo json_encode( $data );

} else {
    header('Content-type: application/json');
    $data = ['success' => false, 'message' => 'There was an error uploading the file (folder), please try again!'];
    echo json_encode( $data );
}

上传方法

uploadFile: ''; // from ngModel
fileUpload(path) {
    const fileTransfer: FileTransferObject = this.transfer.create();
    let options: FileUploadOptions = {
      fileKey: 'file',
      fileName: '.png',
      chunkedMode: false,
    };

    console.log(this.uploadFile);

    fileTransfer
      .upload(this.uploadFile, 'http://domain/fileUpload.php',
        options
      )
      .then(
        data => {
          console.log(data + 'Uploaded Successfully');
          // console.log(JSON.parse(data.));
          // let res = JSON.parse(data);
          let res = data;
          if (res['success']) {
            console.log('True');
          }
        },
        err => {
          console.log(err);
        }
      );
  }

【问题讨论】:

  • addFile 会抛出错误吗?
  • 抱歉忘记添加错误。上面已经编辑了
  • 您能提供完整的堆栈跟踪吗?
  • 在编辑中添加了上面的图片

标签: php angular ionic-framework


【解决方案1】:

Blow 是示例代码:

import { Platform } from 'ionic-angular';

checkPlatform: boolean = fasle;

constructor(public plt: Platform) {
    if (this.plt.is('ios')) {
      this.checkPlatform == true; // if platform ios this will be true
    }
    if (this.plt.is('android')) {
      this.checkPlatform == true; // if platform androidthis will be true
    }

  }

imageUpload(path) {
  const fileTransfer: FileTransferObject = this.transfer.create();
  let options: FileUploadOptions = {
      fileKey: 'image',
      fileName: '.png',
      chunkedMode: false,
      //mimeType: "image/jpeg",
    }


    fileTransfer.upload(path, 'https://yourDomain.com/api/imageUpload', options)
      .then((data) => {
      console.log(data+" Uploaded Successfully");
      console.log(JSON.parse(data.response));
      let res = JSON.parse(data.response);
      if (res.success == true) {
          // do whats ever you want to do
      }


    }, (err) => {
      console.log(err);

    });
}

在此函数中将cordova 文件路径作为参数传递。

在您的 HTML 模板中显示按钮或输入类型,如下所示:

<input type="file" *ngIf="checkPlatform == true">

【讨论】:

  • 得到这个错误 FileTransferError {code: 1, source: "C:\fakepath\panda.jpg", target: "ccoulter12.lampt.eeecs.qub.ac.uk/api/fileUpload.php", http_status: null, body: null, ...}跨度>
  • 以上为上传功能编辑
  • 请分享您的this.uploadFile 中的内容
  • 它来自输入标签ngModel获取文件
  • 输入类型file可能有问题..如果只是图片请使用相机插件。
【解决方案2】:

我检查了您的代码,我看到添加到FormDatafilestring 类型的文件名,而不是FileBlob 数据类型。所以在这种情况下,它不会将文件发送到$_FILES,它实际上将它的值发送到您的PHP Server 中的$_POST。综上所述,FileBlob 类型将被发送到$_FILES,其他数据类型将被发送到相应的全局变量。

PHP Server 中还有一个关于如何验证文件的好示例:https://www.php.net/manual/en/features.file-upload.php

【讨论】:

  • 所以我只是将我的 formData 更改为文件或 blob?
  • 没错。当您通过HTML 标签上传文件时,它实际上是blob 类型,您可以附加到DataForm
【解决方案3】:

如果您看到this,您会注意到允许的类型是:

export type TextFieldTypes = 'date' | 'email' | 'number' | 'password' | 'search' | 'tel' | 'text' | 'url' | 'time'; 如果你想上传文件,请关注this 链接,我想你会找到答案的

【讨论】:

  • 我一直在到处寻找文件插件的示例,但似乎找不到
  • 按照我添加的链接上传文件,它有很好的记录
  • 只是文件插件?没有上传例如?
  • 如果你想上传文件使用github.com/apache/cordova-plugin-file-transfer
  • 我试过了,但不能正常工作?它在上面的代码中
猜你喜欢
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多