简体   繁体   中英

Pass filename from file upload to text field

I have a part of a form where a user can upload a file. I want only the filename to be sent to a text field in the same form. So if user uploaded "C:/Folder/image.jpg", the text field should show "image.jpg". I tried some code myself but I know it's wrong:

function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
        default:;
    } // switch
} // ff_uploadimages_action

ff_uploadimages is the field to upload file, and filename is the textfield where name should appear. Any help at all is appreciated! Thanks.

Here's one way to do it

 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; } 
 <input id="upload" type="file" /> <input id="filename" type="text" /> 


you don't mention jQuery but given it's popularity here's the same solution using jQuery

jQuery:

$('#upload').change(function() {
    var filename = $(this).val();
    var lastIndex = filename.lastIndexOf("\\");
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex + 1);
    }
    $('#filename').val(filename);
});

Demo:

http://jsfiddle.net/pxfunc/WWNnV/4/

HTML:

<input id="upload" type="file" onChange="uploadOnChange(this)" />
<input id="filename" type="text" />

JS:

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

A shorter way in jQuery would be the following:

HTML

<input type="file" id="inputFile" class="hidden"/>
<input type="text" id="inputDisplayFileName" readonly/>
<button id="buttonChooseFile">Choose file</button>

jQuery

$("#buttonChooseFile").click(funtion()({
    $("#inputFile").click();        
});

$("#inputFile").change(function(){
    var fileName = $("#inputFile").prop('files')[0]["name"];

    $("inputDisplayFileName").val(fileName);
});

In this example the default file upload is hidden so that you can style the 'upload file input' as desired. Clicking the button will trigger the original (hidden) file upload. After choosing the file the .onchange() will do the rest of the work, copying the file the 'read only input text'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM