0

I have tried by seeing this link https://www.freakyjolly.com/angular-file-upload-using-formdata/ As a fresher I don't know how to do.I want to upload a excel file from our local location. Can anyone help me?

**HTML**


<form [formGroup]="fileUploadForm" (ngSubmit)="onFormSubmit()">
   
        <div class="col-sm-6 text-center">

            <div class="custom-file">
                <input type="file" class="custom-file-input" id="customFile" name="myfile"
                    (change)="onFileSelect($event)" #UploadFileInput>
                <label class="custom-file-label" for="customFile">{{fileInputLabel || 'Choose File'}}</label>
            </div>

        </div>
        <div class="col-sm-6 text-center">
            <button class="btn btn-primary" type="submit">Upload</button>
        </div>
    </div>
</form>
nandhu Sanraj
  • 17
  • 2
  • 8
  • Use ```accept=".xlsx"``` in your input tag. This is a duplicate of https://stackoverflow.com/questions/30928826/only-allow-specific-file-extensions-in-angular-file-upload-module-to-be-clickabl – Ajinkya Bawaskar Mar 16 '21 at 13:57

1 Answers1

3

Use accept=".xlsx" in your input tag.

Example:

<input
    type="file" 
    accept=".xlsx"
    class="custom-file-input"
    id="customFile"
    name="myfile"
    (change)="onFileSelect($event.target.files)"
    #UploadFileInput
>

UPDATED to answer OP's comment:

TypeScript code:

fileToUpload: File = null;

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

// call this method when you want the upload to begin
uploadFile(fileToUpload: File): Observable<boolean> {
    const endpoint = 'backend-upload-url';
    const formData: FormData = new FormData();
    formData.append('file', fileToUpload, fileToUpload.name);
    return this.httpClient
      .post(endpoint, formData)
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

  • Can you give the code of Component .ts please @Ajinkya Bawaskar – nandhu Sanraj Mar 16 '21 at 14:25
  • Thank you for your reply. const endpoint='backend-upload-url' . This line defines the file from where we are uploading right? If yes,I need the local location in my laptop while clicking the browse button. @Ajinkya Bawaskar – nandhu Sanraj Mar 17 '21 at 06:28
  • No, that line is a URL, provided by whatever backend you are using. Angular will make a HTTP post request with file in its payload to the specified backend. Please accept the answer if it solves the asked question. – Ajinkya Bawaskar Mar 17 '21 at 11:38
  • Sorry, Can you please give me the full demo code, seriously I am a beginner I am not getting it completely. @Ajinkya Bawaskar – nandhu Sanraj Mar 18 '21 at 08:51
  • Can you please post the backend code where you read the excel file @Ajinkya Bawaskar? Would be great! – Mathias Noack Sep 02 '22 at 13:10