从文件上传到文本字段传递文件名 [英] Pass filename from file upload to text field

查看:95
本文介绍了从文件上传到文本字段传递文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单的一部分,用户可以上传文件。我只想将文件名以相同的格式发送到文本字段。所以如果用户上传了C:/Folder/image.jpg,文本字段应该显示image.jpg。我自己尝试了一些代码,但我知道它是错误的:

pre $ function $ data.match(/((*):\ /)/(*)[\ / \\]([^ \ / \\] + \.\w +)$ /) ;
switch(action){
case'change':
if(data.match(/((*):\ /)/(。*)[\ / \\\ \\]([^ \ / \\] + \\\\w +)$ /)。value)
ff_getElementByName('filename')。value = m [2] .text;
默认值;;
} //转换
} // ff_uploadimages_action

ff_uploadimages是上传文件,文件名是应该出现名称的文本字段。任何帮助都是值得赞赏的!谢谢。

解决方案

HTML:

 < input id =uploadtype =file/> 
< input id =filenametype =text/>

javascript:

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

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






你没有提及jQuery,但考虑到它的受欢迎程度,这里使用jQuery的相同解决方案



jQuery:

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






演示:



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


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

HTML:

<input id="upload" type="file" />
<input id="filename" type="text" />

javascript:

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


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/

这篇关于从文件上传到文本字段传递文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆