Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

661
Vistas
How to get file name from the uploaded file using javascript?

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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

maybe you can use this

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda