开发者

Pass filename from file upload to text field

开发者 https://www.devze.com 2023-02-21 04:50 出处:网络
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 \"

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'.

0

精彩评论

暂无评论...
验证码 换一张
取 消