javascript - 使用文本输入字段上传文件,以便用户也可以输入文件路径

标签 javascript jquery

我目前有一个表单,其中上传文件如下所示:

enter image description here

我想让它看起来像这样:

enter image description here

这样做的原因是因为服务器已经拥有这些文件。所以我只想在输入字段中添加 URL。但是,上传按钮也很重要,因为我们需要上传服务器中尚未存在的文件。

我们如何最好地解决这个问题?

我目前有这个代码:

function wp_custom_attachment() {
    wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');
    $html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25" />';
    echo $html;
}

我尝试了这样的方法,但最终出现了警告:

$html .= '<input type="text" value="" id="wp_custom_attachment" name="wp_custom_attachment" onclick="javascript:document.getElementById(\'file\').click();"><input id="file" type="file" name="img" onchange="ChangeText(this, \'wp_custom_attachment\');"/>';

警告:

Warning: Illegal string offset 'url' in /path/content.php on line 42

最佳答案

您可以通过使用 type='file' 隐藏输入以及 buttontype='text'。为了使按钮处于事件状态,我们在按钮的 onclick 处添加一个触发器。输入type='file'onchange我们触发一个函数changeInput来更改输入type='text'的内容.

这会产生以下 html:

<input type="text" id="filename" name="filename"><button onclick="document.getElementById('file').click();">Open</button>
<input id="file" type="file" name="file" style="display: none;" onchange="changeInput()" />
<script>
function changeInput(){
  document.getElementById("filename").value = document.getElementById('file').value;
}
</script>

请注意,此 html 将文件的完整路径放入 type='text' 输入中。保存新文件时,需要对编辑的文件名进行一些解析。

关于javascript - 使用文本输入字段上传文件,以便用户也可以输入文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58801618/

相关文章:

javascript - 如何将数据转换为 JSON

javascript - 从数组中删除第一个元素并返回数组减去第一个元素

jquery - 添加百分比值而不是 px

javascript - 如何检查某个用户是否选择了其他用户即将选择的项目?

javascript - (Electron JS)如何制作一个关闭后自动保存的程序?特别像微软便笺

javascript - slider 需要超时功能动画

jquery - jQuery cookie 是否有可能像 session 变量一样过期?

javascript - 使用 jquery 获取 <td> 中隐藏字段的值

javascript - 如何获取多选项下拉列表的值?

javascript - 将 HTML Canvas 转换为图像。 JavaScript