Home > Software engineering >  How can I get the file name of a file that has been uploaded in a form, but the form itself was not
How can I get the file name of a file that has been uploaded in a form, but the form itself was not

Time:10-03

So, I have this form where you can upload an image file. Before you upload a file there is a label saying 'Choose file", however I want to use JS, so when you upload a file with a file name let's say 'testImage.jpg' the label to change from 'Choose file' to 'testImage.jpg'.

However, I am not sure how in ASP.NET core I can get the file name of the uploaded file before the form is submitted.

An oversimplified version of the form

@model AddCardFormModel

<form method="post" enctype="multipart/form-data">
  <div >
      <div >
          <input type="file" asp-for="ImageFile"  id="customFile" placeholder="">
          <label asp-for="ImageFile"  for="customFile">Choose file</label>
          <span asp-validation-for="ImageFile" ></span>
      </div>
  </div>
  <input  type="submit" value="Save"/>
</form>

CodePudding user response:

Turns out that with JS you can get the file from the input and change the content of the label.

Adding onchange-"changeLabelTextContent(this); to the input element and the code below do the magic perfectly.

function changeLabelTextContent(myFile){
        var file = myFile.files[0];
        
        var fileLabel = document.getElementsByClassName('custom-file-label');

        fileLabel[0].textContent = file.name;
    }
  • Related