i want to get the file name and show it in input element using javascript.
i have a button upload clicking that would open the browser to choose file once chosen i should display the chosen file name in input element.
below is my code,
const kubeConfig = get(values, `${fieldRoot}.kubeConfig`);
const fileName = useMemo(() => {
if (kubeConfig) {
return kubeConfig.name; //cannot read property name of undefined
}
}, [kubeConfig])
<FormField
label="file"
fieldId={`${fieldRoot}.kubeConfig`}
>
{({form}: FieldProps) => (
<>
<input
type="text"
value={fileName ?? 'Upload file'}
/>
<input
type="file"
style={{display: 'none'}}
accept=".pem"
ref={inputRef}
onChange={async() => {
const file = inputRef?.current?.files?.[0];
if (file) {
try {
form.setFieldValue(
`${fieldRoot}.kubeConfig`,
file
);
}
}
}}
/>
<button onClick={handleUploadClick}> Upload </button>
)}
</FormField>
i get error cannot read property name of undefined.
kubeconfig data is like below
I am new to programming learning on the go. could someone help me with this. thanks. how can i access name from kubeConfig data.
File inputs have a files property that can be interrogated to obtain the file name, MIME type, and size (in bytes).
Each item in the files list is a File, which is an object (not a string) that has a .name property.
For more info, see Getting information on selected files from MDN.
In React, you can get this information from the event argument that is provided to the onChange handler. I think that's generally better than using a ref, because it mirrors the pattern you'd use with other kinds of inputs.
I think the reason your code is failing is because you're not managing your data well.
I think you want something like this:
let [ filename, setFilename ] = React.useState<string>('')
function onChangeFile( event: React.ChangeEvent<HTMLInputElement> ): boolean {
if(event.files && event.files.length) {
setFilename(event.files[0].name)
}
return true
}
<FormField
label="file"
fieldId={`${fieldRoot}.kubeConfig`}
>
{({form}: FieldProps) => (
<>
<input
type="text"
value={filename}
/>
<input
type="file"
style={{display: 'none'}}
accept=".pem"
ref={inputRef}
onChange={onChangeFile}
/>
<button onClick={handleUploadClick}> Upload </button>
</>
)}
</FormField>
A few things to note:
getform.setFieldValue; I don't see the implementation of <FormField> here, so there's no way for us to know how to use it properlyhandleUploadClick, so I'm assuming that all it does is fire a click event on the hidden file input (which is pretty common)Also, you should never define DOM event handlers as async. DOM event handlers do not understand Promises. A DOM event handler must return a boolean, not a boolean inside a Promise, if you want the page to react properly.
maybe you can use this
var fu1 = document.getElementById("FileUpload1");
alert("You selected " + fu1.value);