将文件从 angular ionic 上传到本地主机中的纤薄 php 框架

问题描述

你好我在localhost有一个项目,我想将文件上传到本地文件夹,我附上代码看看是否有人可以帮助我。

HMTL:

<ion-item ion-item *ngFor="let item of lista" menuClose>
  Piso: {{item.piso}} - Nro: {{item.numero}}
  <input type="file" (change)="handleFileInput($event.target.files)" id="file-input"
  accept="image/png,image/jpeg,application/pdf">
  <ion-icon item-end (click)="cargarExpensas(item)" title="Cargar" style="cursor:pointer" name="ios-cloud-upload-outline">
  </ion-icon>
</ion-item>

打字稿:

 handleFileInput(files: FileList) {
this.filetoUpload = files.item(0);}


cargarExpensas() {
this.servicIoUpload.postFile(this.filetoUpload).subscribe(data => {
  let toast = this.toastCtrl.create({
    message: 'Expensas cargadas con éxito',duration: 3500,cssClass: "clsToastCtrl",});
  toast.present();
},error => {
  let toast = this.toastCtrl.create({
    message: 'Se produjo un error,intente nuevamente',cssClass: "clsToastCtrlError",});
  toast.present();
  console.log(error);
});  }

供应商:

postFile(filetoUpload: File): Observable<boolean> {
    const endpoint = apiUrl + 'api/upload/files/';
    const formData: FormData = new FormData();
    formData.append('fileKey',filetoUpload,filetoUpload.name);
    return this.http
        .post(endpoint,formData,{ headers:new HttpHeaders({
            'Content-Type': 'application/json'})
        })
        .map(() => { return true; })

}

我缺少PHP中的代码,我使用的是slim框架,有人可以帮助我吗?我也想知道上面的代码是否正确。 非常感谢!

解决方法

我设法让它工作,以防有人需要附加的代码我的 php 代码 :)

 $container = $app->getContainer();
$app->post('/api/upload/files/',function(Request $request,Response $response) {
    $settings = $this->get('settings');
    // $directory = $this->get('upload_directory');
    $uploadedFiles = $request->getUploadedFiles();
    // handle single input with single file upload
    $uploadedFile = $uploadedFiles['fileKey'];

    if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
        $filename = moveUploadedFile($settings["upload_path"],$uploadedFile);
        // $response->write('uploaded ' . $filename . '<br/>');
        $data = array('success' => 'true','filename' => $filename);
        $response->withJson($data,201);
    }
  
});

/**
 * Moves the uploaded file to the upload directory and assigns it a unique name
 * to avoid overwriting an existing uploaded file.
 *
 * @param string $directory directory to which the file is moved
 * @param UploadedFile $uploadedFile file uploaded file to move
 * @return string filename of moved file
 */
function moveUploadedFile($directory,\Slim\Http\UploadedFile $uploadedFile)
{
    $extension = pathinfo($uploadedFile->getClientFilename(),PATHINFO_EXTENSION);
    $basename = bin2hex(random_bytes(8)); // see http://php.net/manual/en/function.random-bytes.php
    $filename = sprintf('%s.%0.8s',$basename,$extension);
    $filepath = $directory . DIRECTORY_SEPARATOR . $filename;
    $uploadedFile->moveTo($filepath);

    return $filename;
}