将文件名从文件上传传递到文本字段

Pass filename from file upload to text field(将文件名从文件上传传递到文本字段)

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

问题描述

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

function ff_uploadimages_action(element, action){var m = data.match(/((*):/)/(.*)[/\]([^/\]+.w+)$/);开关(动作){案例改变":if (data.match(/((*):/)/(.*)[/\]([^/\]+.w+)$/).value)ff_getElementByName('文件名').value = m[2].text;默认:;}//转变}//ff_uploadimages_action

ff_uploadimages 是上传文件的字段,filename 是名称应该出现的文本字段.任何帮助都将不胜感激!谢谢.

解决方案

这是一种方法

document.getElementById('upload').onchange = uploadOnChange;函数uploadOnChange() {var 文件名 = this.value;var lastIndex = 文件名.lastIndexOf("\");if (lastIndex >= 0) {文件名 = 文件名.substring(lastIndex + 1);}document.getElementById('filename').value = 文件名;}

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

<小时>

你没有提到 jQuery,但鉴于它很受欢迎,这里使用 jQuery 的解决方案相同

jQuery:

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

<小时>

演示:

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

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/

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

本文标题为:将文件名从文件上传传递到文本字段

基础教程推荐