Home > DeveloperSection > Forums > How to show name of a file before uploading it.
Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    March-11-2013 1:12 AM

 JavaScript JavaScript 
Ratings:


 1 Reply(s)
 853  View(s)
Rate this:

Hi Everyone!

I want to show the name of a file using JavaScript or jQuery before it is uploaded by the server. I've researched about it and instead I learned how to preview an image before it is uploaded. But the file I wish to upload may not be an image so I need to show the name.

Here is the code to show preview of an image, can it be modified to show the name instead?:

HTML:

<form method="post" name="form" enctype="multipart/form-data">
 <input type="file" name="attachment" onchange="read_input(this);" />
</form>
Javascript + jQuery:

function read_input(input) {

    if (input.files && input.files[0]) {

        var reader = new FileReader();

        reader.onload = function (e) {

            result = e.target.result;

            $(".attachment").html('<img src="'+result+'" alt="preview" />');

        }

        reader.readAsDataURL(input.files[0]);

    }

}

Thanks in advance!



AVADHESH PATEL

Total Post:604

Points:4228
Posted on    March-11-2013 8:36 AM

Hi Jeet!

You can try following line of code

document.getElementById('upload').onchange = uploadOnChange;

function uploadOnChange() {
    var filename = this.value;
    var lastIndex = filename.lastIndexOf("\\");
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex + 1);
    }
    document.getElementById('filename').value = filename;
}

Don't want to miss updates? Please click the below button!

Follow MindStick