0

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

enter image description here

I am new to programming learning on the go. could someone help me with this. thanks. how can i access name from kubeConfig data.

Tom
  • 8,509
  • 7
  • 49
  • 78
natalia
  • 43
  • 1
  • 9

2 Answers2

0

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:

  • we don't need two functions for this (one to store and one to retrieve), we only need one change handler
  • we use regular React state to hold onto the filename, instead of whatever you're doing with lodash get
  • this does not use the form.setFieldValue; I don't see the implementation of <FormField> here, so there's no way for us to know how to use it properly
  • I don't see the implementation of handleUploadClick, 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.

Tom
  • 8,509
  • 7
  • 49
  • 78
  • yes this works. but i am trying to read the file name from kubeConfig. as in edit mode if a file is uploaded already i need to read it from kubeConfig directly. i am getting undefined while accessing name from kubeConfig – natalia Feb 24 '22 at 08:23
  • I think there is not enough information in your post for anyone to figure out how to do that. I can say that, whatever mechanism you use to acquire current data from the server about what files have been uploaded previously, you need a better way to integrate that data feed into your React state than what you have. Figuring out the best way will require knowing a lot more about how your UI app is architected, particuarly what you're using for state management and how the component you've partially included fits into the render tree. – Tom Feb 24 '22 at 08:31
  • i realised that i have been accesssing the kubeConfig when its undefined as well which was causing the issue. thanks for your answer. – natalia Feb 24 '22 at 10:04
0

maybe you can use this

var fu1 = document.getElementById("FileUpload1");
alert("You selected " + fu1.value);