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>
1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Can you give the code of Component .ts please @Ajinkya Bawaskar
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
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.
Sorry, Can you please give me the full demo code, seriously I am a beginner I am not getting it completely. @Ajinkya Bawaskar
Can you please post the backend code where you read the excel file @Ajinkya Bawaskar? Would be great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.