The attempt to upload a file in Angular was unsuccessful

Below is the backend code snippet used to upload a file:

$app->post('/upload/{studentid}', function(Request $request, Response $response, $args) {

    $uploadedFiles = $request->getUploadedFiles();

    $uploadedFile = $uploadedFiles['filename'];
    if ($uploadedFile->getError() === UPLOAD_ERR_OK) {

        $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);

        $filename = sprintf('%s.%0.8s', $args["studentid"], $extension);

        $directory = $this->get('settings')['upload_directory'];
        $uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);

        $sql = "UPDATE feepaid SET filename=:filename WHERE studentid=:studentid";
        $stmt = $this->db->prepare($sql);
        $params = [
            ":studentid" => $args["studentid"],
            ":filename" => $filename
        ];

        if($stmt->execute($params)){
            $url = $request->getUri()->getBaseUrl()."/Upload/".$filename;
            return $response->withJson(["status" => "success", "data" => $url], 200);
        } else {
            return $response->withJson(["status" => "failed", "data" => "0"], 200);
        } 
    }
});

I have tested this using Postman and it worked fine. However, when implementing the API in my Angular application, I encountered some issues.

You can view my Angular file upload code below:

  fileChange(event) {
    const fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      const file: File = fileList[0];
      const formData: FormData = new FormData();
      formData.append('uploadFile', file, file.name);
      const headers = new Headers();
      
      const id = sessionStorage.getItem('userId');
      
      this.http.post('http://localhost:8080' + '/upload/' + id , formData)
        .subscribe(
          data => console.log('success'),
          error => console.log(error)
        );
    }

  }

If you encounter any errors or have suggestions, please feel free to reach out. Your assistance would be greatly appreciated!

Answer №1

Make sure to submit the correct key-value pair for Form Data by specifying the key as filename. Consider modifying the following line:

formData.append('filename', file, file.name);

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

Understanding TypeScript typing when passing arguments to the Object.defineProperty function

After reviewing all the suggested answers, including: in Typescript, can Object.prototype function return Sub type instance? I still couldn't find a solution, so I'm reaching out with a new question. My goal is to replicate Infix notation in J ...

Setting up eslint for your new react project---Would you like any further

I am currently working on a TypeScript-based React application. To start off, I used the following command to create my React app with TypeScript template: npx create-react-app test-app --template typescript It's worth noting that eslint comes pre-co ...

Exploring generic types using recursive inference

The scenario: export type SchemaOne<T> = | Entity<T> | SchemaObjectOne<T>; export interface SchemaObjectOne<T> { [key: string]: SchemaOne<T>; } export type SchemaOf<T> = T extends SchemaOne<infer R> ? R : nev ...

Issue with Typescript Conditional Type not being functional in a function parameter

For a specific use-case, I am looking to conditionally add a key to an interface. In attempting to achieve this, I used the following code: key: a extends b ? keyValue : never However, this approach breaks when a is generic and also necessitates explicit ...

Tips for modifying only one property after receiving an object from an HTTP GET request

Within my Angular application, I have defined an object structure like this: export class Article { id: number; author: number; title: string; content: string; date: Moment; readingTime: number; draft: boolean; constructor(obj: Partial< ...

Angular Form Template Unidirectional Data Binding Example

I'm facing a challenge with one-way binding to a default value in my HTML form. Within my component, I have a Connection string that is initially set from local storage: export class AuthAdminComponent implements OnInit { public authenticated = f ...

Data transmission is only possible when the connection is in the 'Connected' state

Trying to set up a simple connection using SignalR in Angular 6, I wrote the following code: signalR.helper.ts public static setupHub<T>(hubUrl: string, eventName: string, callback: (data: T) => void, ...params: SignalRParam[]): HubConnection ...

What is the best way to exhibit information from a lone table column in a modal using Angular 7?

Is there a way to have an "edit" button beside each row in the appointments table that triggers a modal popup allowing users to change appointment dates? Unfortunately, I'm facing an issue where the modal does not pop up and my screen turns white. ** ...

Issue with Angular 6: unable to make HTTP POST request from secondary dialog

I'm facing an issue when trying to send HTTP requests from a dialog window in Angular 6. Here's the scenario: I click a button to open the first dialog, then within that dialog I click another button to open a second dialog. In the second dialog ...

Changing the order of a list in TypeScript according to a property called 'rank'

I am currently working on a function to rearrange a list based on their rank property. Let's consider the following example: (my object also contains other properties) var array=[ {id:1,rank:2}, {id:18,rank:1}, {id:53,rank:3}, {id:3,rank:5}, {id:19,r ...

Checkbox with an indeterminate state in Angular

I'm currently working on updating an AngularJS (1.5) setup where a parent checkbox becomes indeterminate if one of its children is selected, and all the children are selected if the parent is selected. My main challenge lies in converting the old ES5 ...

Tips for dynamically updating the included scripts in index.html using Angular 2

As I work on incorporating an Angular website into a Cordova app, one challenge I face is getting the Cordova app to load the Angular remote URL. The index.html file for the Angular site includes the cordova.js file, which is specific to each platform - ...

Is there a way to automatically extend my content to fill the space on the page below the Material UI AppBar?

I am currently using React and Material UI React to develop my application. My goal is to implement the AppBar component with content underneath, without causing the entire page to scroll. I want the content to occupy the maximum remaining height and the f ...

What steps should I take to plan a collaborative code-sharing project?

As I develop various applications utilizing a core framework of my own creation, I am looking for a way to easily manage updates across all these applications. I have structured the code by creating a GitHub project where the main branch consists of the co ...

What are the repercussions of labeling a function, TypeScript interface, or TypeScript type with export but never actually importing it? Is this considered poor practice or is there a potential consequence?

I find myself grappling with a seemingly straightforward question that surprisingly has not been asked before by others. I am currently immersed in a TypeScript project involving Vue, and one of the developers has taken to labeling numerous interfaces and ...

Sharing a FormGroup between different components

For my Angular 2+ application utilizing reactive forms, I have a requirement to share the main FormGroup across multiple components. This will allow different sections of the form such as header and footer to be managed independently by separate components ...

Encountered a NodeJS error while attempting to locate information in a mongo DB: UnhandledPromiseRejectionWarning

In my MEAN stack application, I am working on implementing a login feature that includes social login functionality. When a new user attempts to log in using Facebook, I need to verify if their Facebook account is already registered in my MongoDB database. ...

The functionality of Angular 9 Service Worker appears to be inhibited when hosting the site from a S3 Static Website

I created a Progressive Web Application (PWA) following these steps: Started a new Angular app using CLI 9.1.8; Added PWA support by referring to the documentation at https://angular.io/guide/service-worker-getting-started; Built it with ng build --prod; ...

Encountering this issue? Error TS2304: Name not found

When I attempt to run unit tests for my Angular application using 'ng test', I encounter the error message: "Error TS2304: Cannot find name.." Interestingly, running 'ng serve' works without any issues. I followed a guide (link provide ...

Avoiding loading certain images within an *ngFor loop

Is it possible to control the loading of images within an *ngFor loop in Angular? Load image with index X first Fire a function once all other images have loaded The goal is to prioritize the display of important images while optimizing bandwidth usage. ...