Как ввести форму с изображениями в API php в Ionic 3? - PullRequest
0 голосов
/ 22 февраля 2019

Как отправить мои файлы и изображения на контроллер веб-API сохранить в базе данных по идентификатору.Или форма ввода с изображениями в Ionic 3?я начинающий в ионном

My .ts

    submit() {
    var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers });
    let data = {
      title: this.title.value,
      photo: this.photo.value,
    };

    let loader = this.loadingCtrl.create({ 
      content: 'Please Wait..',
    });

    loader.present().then(() => {
      this.http.post('http://sample.com/api/upload.php', data, options)
        .map(res => res.json())
        .subscribe(res => {
          loader.dismiss()
          if (res['status'] == "true") ......
        });
    });
  }

мой .html

  <ion-item>
    <ion-label floating >Title</ion-label>
    <ion-input type="text" #title></ion-input>
  </ion-item>
  <ion-item>
      <ion-label stacked >Upload </ion-label>
    <ion-input type="file" #upload></ion-input>
  </ion-item>
 <button ion-button  (click)="submit()">BAYAR</button>

мой php

....
$photo = $_FILES['photo']['name'];
$lokasi =$_FILES['foto']['tmp_name'];
move_uploaded_file($lokasi,"../picture/photo/".$photo);
$title= escape($_POST['title']);
$query = "INSERT INTO pesanan 
(title) 
VALUES 
('$title','$photo')";
$result = mysqli_query($link, $query);
....

я пробовал, но только названиечто успешно введено ... Пожалуйста, помогите мне

1 Ответ

0 голосов
/ 23 февраля 2019

Я использую это для отправки изображений на сервер с мобильного телефона

Пример кода.Пожалуйста, проверьте его

home.ts file

import {Component} from '@angular/core';
import {
    AlertController,
    IonicPage,
    NavController,
    NavParams,
    ViewController,
    ActionSheetController,
    ToastController,
    Platform,
    LoadingController,
    Loading
} from 'ionic-angular';
import {ImagePicker} from '@ionic-native/image-picker';
import {File} from '@ionic-native/file';
import {FileTransfer, FileUploadOptions, FileTransferObject} from '@ionic-native/file-transfer';
import {FilePath} from '@ionic-native/file-path';
import {Camera, CameraOptions} from '@ionic-native/camera';
import {Base64} from '@ionic-native/base64';

declare var cordova: any;

@IonicPage()

@Component({
    selector: 'page-image-picker',
    templateUrl: 'image-picker.html',
})

export class ImagePickerFromGallery {

    multi_images: any[] = [];
    lastImage: string = null;
    loading: Loading;

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public viewCtrl: ViewController,
                public alertCtrl: AlertController,
                private transfer: FileTransfer,
                private file: File,
                private base64: Base64,
                private camera: Camera,
                private filePath: FilePath,
                public actionSheetCtrl: ActionSheetController,
                public toastCtrl: ToastController,
                public platform: Platform,
                public loadingCtrl: LoadingController,
                private imagePicker: ImagePicker) {
    }

    selectPhoto() {
        this.imagePicker.hasReadPermission().then(res => {
            if (res) {
                this.openGallery();
            } else {
                this.imagePicker.requestReadPermission().then(resl => {
                    if (resl === 'OK') {
                        this.openGallery();
                    }
                }).catch(error => this.alertMessage("Error", "User cancelled the action!"));
            }
        }).catch(error => this.alertMessage("Error", "User Don't Have Permission!"));
    }

    openGallery() {
        let options = {
            maximumImagesCount: 1,
            correctOrientation: true,
            quality: 100,
            allowEdit: true
        };
        this.imagePicker.getPictures(options).then(image_results => {
            if (image_results.length > 0 && image_results != 'OK') {
                for (let im = 0; im < image_results.length; im++) {
                    let image_path_index = image_results[im];
                    let correctPath = image_path_index.substr(0, image_path_index.lastIndexOf('/') + 1);
                    let filename = image_path_index.split("/").pop();
                    this.copyFileToLocalDir(correctPath, filename, this.createFileName());
                }
            }
        });
    }

    public presentActionSheet() {
        let actionSheet = this.actionSheetCtrl.create({
            title: 'Select Image Source',
            buttons: [
                {
                    text: 'Use Camera',
                    handler: () => {
                        this.takePicture(this.camera.PictureSourceType.CAMERA);
                    }
                },
                {
                    text: 'Load From Library',
                    handler: () => {
                        this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
                    }
                },
                {
                    text: 'Multiple Images Select From Library',
                    handler: () => {
                        this.selectPhoto();
                    }
                },
                {
                    text: 'Cancel',
                    role: 'cancel'
                }
            ]
        });
        actionSheet.present();
    }

    public takePicture(sourceType) {
        // Create options for the Camera Dialog
        let options = {
            quality: 50,
            sourceType: sourceType,
            saveToPhotoAlbum: true,
            correctOrientation: true,
        };
        // Get the data of an image
        this.camera.getPicture(options).then((imagePath) => {
            // Special handling for Android library
            if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
                this.filePath.resolveNativePath(imagePath).then(filePath => {
                    let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
                    let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
                    this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
                });
            } else {
                let correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
                let currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
                this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
            }
        }, (err) => {
            this.presentToast('Error while selecting image.');
        });
    }

    // Create a new name for the image
    private createFileName() {
        var d = new Date(),
            n = d.getTime(),
            newFileName = n + ".jpg";
        return newFileName;
    }

    // Copy the image to a local folder
    private copyFileToLocalDir(namePath, currentName, newFileName) {
        // alert('copyFileToLocalDir');
        // alert(namePath);
        // alert(currentName);
        // alert(newFileName);
        if (namePath && currentName && newFileName) {
            this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
                // alert('lastImage');
                // alert(newFileName);
                // alert(this.pathForImage(newFileName));
                this.multi_images.push(newFileName);
                this.lastImage = newFileName;
            }, error => {
                this.presentToast('Error while storing file.');
            });
        }
    }

    private presentToast(text) {
        let toast = this.toastCtrl.create({
            message: text,
            duration: 3000,
            position: 'top'
        });
        toast.present();
    }

    // Always get the accurate path to your apps folder

    public pathForImage(img) {
        if (img === null) {
            return '';
        } else {
            return cordova.file.dataDirectory + img;
        }
    }

    public uploadImage() {
        // Destination URL

        // let url = "https://server.in/images/create/";
           let url = "https://server.in/controller/function/";

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

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

        let options = {
            fileKey: "change_cover",
            fileName: filename,
            chunkedMode: false,
            mimeType: "multipart/form-data",
            params: {'fileName': filename,'timeline_type':'event','timeline_id':'912'}
        };

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

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

        this.loading.present();

        // Use the FileTransfer to upload the image
        fileTransfer.upload(targetPath, url, options).then(data => {
            alert(data);
            alert(JSON.stringify(data));
            this.loading.dismissAll();
            this.presentToast('Image successfully uploaded.');
        }, err => {
            this.loading.dismissAll();
            this.presentToast('Error while uploading file.');
        });
    }

    alertMessage(title, message) {
        let alert = this.alertCtrl.create({
            title: title,
            enableBackdropDismiss: false,
            message: message,
            buttons: [
                {
                    text: 'ok',
                    role: 'cancel',
                    handler: () => {
                        this.viewCtrl.dismiss();
                    }
                }
            ]
        });
        alert.present();
    }
}

В codeignitor я создал файл контроллера изображений внутри, который создал функцию create () для перемещения изображений в определенную папку.А также я создал папку загрузки в главной директории codeignitor.Внутри папки загрузки я создал папку image_picker для хранения изображений.

пример функции

public function create()
    {
        header('Access-Control-Allow-Origin: *');
        $target_path = "uploads/image_picker/";
        $target_path = $target_path . basename($_FILES['file']['name']);
        if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
            $data['success'] = "Upload and move success";
            $data['path'] = $target_path;
        } else {
            $data['path'] = $target_path;
            $data['error'] = "There was an error uploading the file, please try again!";
        }
        echo json_encode($data);
    }

файл Package.json

{
  "name": "imageupload",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "start": "ionic-app-scripts serve",
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint"
  },
  "dependencies": {
    "@angular/animations": "5.2.11",
    "@angular/common": "5.2.11",
    "@angular/compiler": "5.2.11",
    "@angular/compiler-cli": "5.2.11",
    "@angular/core": "5.2.11",
    "@angular/forms": "5.2.11",
    "@angular/http": "5.2.11",
    "@angular/platform-browser": "5.2.11",
    "@angular/platform-browser-dynamic": "5.2.11",
    "@ionic-native/camera": "^4.17.0",
    "@ionic-native/core": "~4.17.0",
    "@ionic-native/file": "^4.17.0",
    "@ionic-native/file-path": "^4.17.0",
    "@ionic-native/file-transfer": "^4.17.0",
    "@ionic-native/photo-library": "^4.17.0",
    "@ionic-native/splash-screen": "~4.17.0",
    "@ionic-native/status-bar": "~4.17.0",
    "@ionic-native/transfer": "^3.14.0",
    "@ionic/storage": "2.2.0",
    "cordova-android": "6.3.0",
    "cordova-plugin-camera": "^4.0.3",
    "cordova-plugin-device": "^2.0.2",
    "cordova-plugin-file": "^6.0.1",
    "cordova-plugin-file-transfer": "^1.7.1",
    "cordova-plugin-filepath": "^1.4.2",
    "cordova-plugin-ionic-keyboard": "^2.1.3",
    "cordova-plugin-ionic-webview": "^2.2.5",
    "cordova-plugin-photo-library": "^2.1.1",
    "cordova-plugin-splashscreen": "^5.0.2",
    "cordova-plugin-statusbar": "^2.4.2",
    "cordova-plugin-whitelist": "^1.3.3",
    "ionic-angular": "3.9.2",
    "ionicons": "3.0.0",
    "rxjs": "5.5.11",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.2.0",
    "typescript": "~2.6.2"
  },
  "description": "An Ionic project",
  "cordova": {
    "plugins": {
      "cordova-plugin-camera": {},
      "cordova-plugin-file": {},
      "cordova-plugin-file-transfer": {},
      "cordova-plugin-filepath": {},
      "cordova-plugin-whitelist": {},
      "cordova-plugin-statusbar": {},
      "cordova-plugin-device": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-ionic-webview": {},
      "cordova-plugin-ionic-keyboard": {},
      "cordova-plugin-photo-library": {
        "PHOTO_LIBRARY_USAGE_DESCRIPTION": "To choose photos"
      }
    },
    "platforms": [
      "android"
    ]
  }
}

файл app.module.ts

import {BrowserModule} from '@angular/platform-browser';
import {ErrorHandler, NgModule} from '@angular/core';
import {IonicApp, IonicErrorHandler, IonicModule} from 'ionic-angular';
import {SplashScreen} from '@ionic-native/splash-screen';
import {StatusBar} from '@ionic-native/status-bar';

import {MyApp} from './app.component';
import {HomePage} from '../pages/home/home';

import {File} from '@ionic-native/file';
import {Transfer} from '@ionic-native/transfer';
import {FilePath} from '@ionic-native/file-path';
import {Camera} from '@ionic-native/camera';
import {PhotoLibrary} from '@ionic-native/photo-library';

@NgModule({
    declarations: [
        MyApp,
        HomePage
    ],
    imports: [
        BrowserModule,
        IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        MyApp,
        HomePage
    ],
    providers: [
        StatusBar,
        SplashScreen,
        File,
        Transfer,
        Camera,
        FilePath,
        PhotoLibrary,
        {provide: ErrorHandler, useClass: IonicErrorHandler}
    ]
})
export class AppModule {
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...