Transferring documents from an angular ionic application to a slim php framework on the localhost

Hey there! I've got a project on my localhost where I need to upload files to a local folder. I'm sharing the code here in hopes that someone can assist me.

HTML:

<ion-item ion-item *ngFor="let item of lista" menuClose>
  Floor: {{item.piso}} - Number: {{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="Upload" style="cursor:pointer" name="ios-cloud-upload-outline">
  </ion-icon>
</ion-item>

Typescript:

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


cargarExpensas() {
this.servicioUpload.postFile(this.fileToUpload).subscribe(data => {
  let toast = this.toastCtrl.create({
    message: 'Expense uploaded successfully',
    duration: 3500,
    cssClass: "clsToastCtrl",
  });
  toast.present();
}, error => {
  let toast = this.toastCtrl.create({
    message: 'An error occurred, please try again',
    duration: 3500,
    cssClass: "clsToastCtrlError",
  });
  toast.present();
  console.log(error);
});  }

Provider:

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; })

}

I need help with the PHP code for this using the Slim framework. Can anyone lend a hand? Also, any feedback on the code above would be greatly appreciated. Thanks a bunch!

Answer №1

For anyone in need of the code snippet below, this PHP code worked well for me:

 $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;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging File functionality in TypeScript

In the process of developing a web application with Angular 4 and Typescript, I encountered an issue while attempting to retrieve the date of a file for upload. Specifically, when trying to access the lastModified property of a File object, Typescript retu ...

Creating an Ionic popover from a template: How can I dynamically pass parameters in the URL?

Here is the code snippet that I am working with: $ionicPopover.fromTemplateUrl('templates/popover_available_sounds.html', { scope: $scope, }).then(function(popover) { $scope.popover = popover; }); ...

What is the best way to retrieve the ID of an element using ViewChild in Angular 2 and

How can I establish a relationship between jQuery and ViewChild in Angular 2? I attempted the following code, but it returned an undefined value: @ViewChild('item', {read: ViewContainerRef}) Item; console.log( $(this.Item.nativeElement).attr(& ...

Changing the title dynamically for the Global NavBar in Ionic 2

I have been working with the Nav component in Ionic 2 and I'm facing a challenge. I want to maintain a global header with left and right menus while changing the title dynamically as I navigate through different root pages. Here is the code snippet th ...

Can ng-content be utilized within the app-root component?

I have successfully developed an Angular application, and now I am looking to integrate it with a content management system that generates static pages. In order to achieve this, I need to utilize content projection from the main index.html file. The desi ...

Determine whether there are a minimum of two elements in the array that are larger than zero - JavaScript/Typescript

Looking for an efficient way to determine if there are at least two values greater than 0 in an array and return true? Otherwise, return false. Here's a hypothetical but incorrect attempt using the example: const x = [9, 1, 0]; const y = [0, 0, 0]; c ...

Preventing Component Reuse in Angular 2 RC2 version "2.0.0-rc.2 (2016-06-15)"

During my work with angular 2 RC1 version, I encountered a situation where I needed to implement navigation within nested structures. Specifically, I wanted to be able to navigate from one Component (A) to the same Component (A), but without Angular reusin ...

Whenever signing in with Next Auth, the response consistently exhibits the values of "ok" being false and "status" being 302, even

I am currently using Next Auth with credentials to handle sign-ins. Below is the React sign-in function, which can be found at this link. signIn('credentials', { redirect: false, email: email, password: password, ...

Combining the output of two Observables through the CombineLatest method to generate a

I possess two separate collections of information: Data Model: taxControlReference [ { "providerId": "HE", "taxTables": { "STAT": [ 1 ] } }, ...

What is the best way to obtain a distinct collection from two arrays that eliminates the second appearance of an element based on a key's value, rather than the first as in the Lodash uniqueBy function?

Let's say I have two arrays... const arr1 = [ { id: 1: newBid: true } ]; const arr2 = [ { id: 1, newBid: false }, { id: 2, newBid: false } ]; My goal is to end up with an array that looks like this [ { id: 1, newBid: false }, { id: 2, newBid: fals ...

What steps can I take to resolve the 'Object may be null' error in TypeScript?

I am facing a similar issue to the one discussed in this thread, where I am using Draft.js with React and Typescript. After following the code example provided in their documentation, I encountered the 'Object is possibly 'null'' error ...

What is the proper way to store the output in a variable? Angular and XLSX

I am attempting to read an Excel file from an input using Angular and convert the data into an array of objects. Here is how my components are structured: import * as XLSX from 'xlsx'; import { Injectable } from '@angular/core'; @Injec ...

Angular 5: Transforming and Concealing CSS Class Names

Can CSS selectors be renamed or obfuscated in an Angular CLI project? Many top websites like Google and Facebook use randomized CSS names for various reasons, such as preventing website scripting through targeting static class names. I would like to imple ...

Receiving a NaN output rather than a numerical value

Experiencing what seems to be a straightforward syntax error, but I'm unable to pinpoint it. Controller: $scope.startCounter = 3; $scope.startTimeouter = function (number) { $scope.startCounter = number - 1; mytimeouter = $t ...

Navigating back to the starting point

I'm experiencing an issue while trying to navigate using the Router.navigate method. Despite following all instructions meticulously, whenever I attempt to route via API, it reloads the root page. Within my RootComponent implementation, I am utilizin ...

How to handle Object data returned asynchronously via Promises in Angular?

Upon receiving an array of Question objects, it appears as a data structure containing question categories and questions within each category. The process involves initializing the object with board: JeopardyBoard = new JeopardyBoard();. Subsequently, popu ...

Single array returned by observable

Issue: I am looking for a way to consolidate the multiple arrays returned individually into a single array. Solution: fetchAllRiders() { var distanceObs = Observable.create(observer => { this.http.get(this.API + '/driver/all').map(res = ...

Determining if an emitted event value has been altered in Angular 4

I am currently working on an Angular 4 project. One of the features I have implemented is a search component, where users can input a string. Upon submission of the value, I send this value from the SearchComponent to the DisplayComponent. The process of ...

Issues with installing the forked version of the npm/Angular 8 package differ from the original installation method

After utilizing git, forking, branching, pull requests, and npm in my standard nodejs projects without any major issues, I encountered an unexpected problem. When trying to Fork an Angular repository and integrate this forked version into my project, I not ...

Why is the button's ng-click changing the URL but not displaying the new view?

I recently started developing an IONIC application and encountered a challenge in navigating between pages upon clicking a button. Here is the progress I have made so far: In my index.html file, I have included various scripts and links for the applicatio ...