Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

662
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

maybe you can use this

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda