Home > database >  Display the name of the pdf file from a base64 string
Display the name of the pdf file from a base64 string

Time:12-04

I have a function below that sets an array of pdf files using the base64 string of the selected files. I want to display the name of the file the user selected in a list as a string (For example, if the user selected a file named john.pdf, I want that file name as a string displayed). Right now obviously it only displays very long base64 strings. How can I display "john.pdf"?

 
  const handleFile = (e) => {
    let selectedFile = e.target.files[0];
    if (selectedFile) {
      if (selectedFile && allowedFiles.includes(selectedFile.type)) {
        let reader = new FileReader();
        reader.readAsDataURL(selectedFile);
        reader.onloadend = (e) => {
          const newPdfFiles = [...currentPdfFiles];
          newPdfFiles.push(e.target.result);
          console.log(`current pdfs: ${currentPdfFiles}`);
          setCurrentPdfFiles(newPdfFiles);
          console.log(currentPdfFiles);
        };
      } else {
        //setPdfError("Not a valid pdf");
      }
    } else {
      console.log("please select file");
    }
  };
   <div className="card mt-4">
          <ul className="list-group list-group-flush">
            {currentPdfFiles.length > 1 &&
              currentPdfFiles.map((pdfFile) => {
                return <li className="list-group-item">{pdfFile}</li>;
              })}
          </ul>
        </div>
      </div>

CodePudding user response:

const handleFile = (e) => {
  let selectedFile = e.target.files[0];
  if (selectedFile) {
    if (selectedFile && allowedFiles.includes(selectedFile.type)) {
      let reader = new FileReader();
      reader.readAsDataURL(selectedFile);
      reader.onloadend = (e) => {
        const newPdfFiles = [...currentPdfFiles];
        newPdfFiles.push(e.target.result);
        console.log(`current pdfs: ${currentPdfFiles}`);
        setCurrentPdfFiles(newPdfFiles);
        console.log(currentPdfFiles);
      };
    } else {
      //setPdfError("Not a valid pdf");
    }
  } else {
    console.log("please select file");
  }
};

// ...

<div className="card mt-4">
  <ul className="list-group list-group-flush">
    {currentPdfFiles.length > 1 &&
      currentPdfFiles.map((pdfFile, index) => {
        return <li className="list-group-item">{selectedFile[index].name}</li>;
      })}
  </ul>
</div>

I added an index to the map function, so that we can access the file name from the selectedFile array by its index. I used the name property of the File object to display the file name in the list.

  • Related