0

I have this js code that will be responsible to create an hidden file input and then create a base64 from the selected file

const fileReader = new FileReader()
let docxTemplate

export async function run() {
    return Word.run( async (ctx) => {
        //
        const fileInput = document.createElement('input')
        fileInput.type = 'file'
        fileInput.hidden = true
        fileInput.multiple = false
        fileInput.accept = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        fileInput.click()
        //
        fileInput.onchange = () => {
          //the console log will return undefined
          console.log(fileReader.readAsDataURL(fileInput.files[0]))
          fileReader.onload = () => {
             docxTemplate = fileReader.result
          }

        }
        //
        //Also this console log will return undefined
        console.log(docxTemplate)
        //
        const doc = ctx.document.body
        //
        let date = doc.search('[DATE]')
        let dateNow = dayjs().locale('it').format('D MMMM YYYY')
        console.log(dateNow)
        date.load('text')

        return ctx.sync().then( () => {
            //
        })
    })
}

I've created the docxTemplate variable and I want to assign the resulting base64 to it so I can use the variable with the DocumentCreated class of word js api. Unfortunately I'm unable to get the desired result and the variable will be set only inside the file reader onload function. How I can assign the result of the file reader correctly to the variable?

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
ICTDEV
  • 227
  • 1
  • 10
  • 2
    Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Ivar Apr 19 '23 at 15:03

0 Answers0