使用 javascript/jquery 触发文件上传对话框 [英] trigger file upload dialog using javascript/jquery

查看:44
本文介绍了使用 javascript/jquery 触发文件上传对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代替使用 ,是否可以使用 然后编写脚本使用javascript或jquery,这样当文本框被点击时,文件上传对话框就会出现......(并在提交到表单时实际上传)

instead of using <input type="file">, is it possible to use <input type="text"> and then script it using javascript or jquery such that when the text box is clicked, the file upload dialogue shows up.....(and have it actually uploaded when it's submitted into a form)

推荐答案

你的意思是这样的?

http://jsfiddle.net/CSvjw/

$('input[type=text]').click(function() {
    $('input[type=file]').trigger('click');
});

$('input[type=file]').change(function() {
    $('input[type=text]').val($(this).val());
});

但是请注意,出于安全原因,文件输入给出的值是假的.如果只想显示文件名,可以去掉斜杠.

Note, though, that the value given by the file input is fake for security reasons. If you want to just have the file name show up, you can cut out the slashes.

以下是如何使用字符串拆分和数组弹出的示例:

Here's an example of how to do it using a string split and an array pop:

http://jsfiddle.net/CSvjw/1/

$('input[type=text]').click(function() {
    $('input[type=file]').trigger('click');
});

$('input[type=file]').change(function() {
    var vals = $(this).val(),
        val = vals.length ? vals.split('\').pop() : '';

    $('input[type=text]').val(val);
});

您可以进一步调整以适应使用正斜杠作为目录分隔符的系统.同样重要的是要注意,如果你这样做,你将失去许多现代浏览器的功能,用户可以将文件从他们的计算机直接拖到文件输入上.如果我是你,我会通过设置文件输入的样式来接受这种范式,而不是试图将文本输入转换为它不是的东西.

You can adjust this further to account for systems that use a forward slash as the directory separator. It's also important to note that if you do this, you'll lose the functionality of many modern browsers where users can drag files from their computer directly onto a file input. If I were you, I'd embrace that paradigm by styling the file input rather than trying to turn a text input into something that it is not.

这篇关于使用 javascript/jquery 触发文件上传对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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