Elaine Byene
Elaine Byene

Reputation: 4142

File upload with text input field so user can enter file path too

I currently have a form where the upload file looks like this:

enter image description here

I would like to make it look like this:

enter image description here

The reason for doing this is because the server already has the files. So I simply want to add the URL in the input field. However, the upload button is important too because we will need to upload files which aren't in the server yet.

How do we best go about this?

I currently have this code:

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

I tried a method like this but this ended up with a warning:

$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:

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

Upvotes: 0

Views: 1316

Answers (1)

Tom Groot
Tom Groot

Reputation: 1180

You can do this by using a hidden input of type='file', together with a button and an input of type='text'. To make the button active we add a trigger at the onclick of the button. onchange of the input type='file' we trigger a function changeInput to change the content of the input type='text'.

Which results in the following 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>

Be aware that this html puts the full path of the file in the type='text' input. When saving the new file, some parsing of the edited filename is required.

Upvotes: 1

Related Questions