Home  >  Q&A  >  body text

How can I make sure the file is not corrupted after downloading?

handleDownload() Function is added as an event handler (onclick) to the button so that the user can download the file. The user can download but the file is corrupted. How do we prevent file corruption?

function handleDownload(){  
    const domain = window.location.origin;
    const url =`${domain}/images/athar.pdf`
    fetch(url).
    then(response=>response.blob()).
    then(blob=>{
      const blobURL= window.URL.createObjectURL(
        new Blob([blob]))

      const filename = 'athar.pdf'
      const aTag  = document.createElement('a')
      aTag.href=blobURL
      aTag.setAttribute('download',filename)
    
      document.body.appendChild(aTag)
      aTag.click()
      aTag.remove()
      }).
    catch(e=>console.log(e))

            
  }

P粉135292805P粉135292805376 days ago584

reply all(1)I'll reply

  • P粉384366923

    P粉3843669232023-09-11 00:42:43

    Since you already received the response as a Blob, there is no need to convert it to a Blob again, so try removing that part.

    Try to replace:

    const blobURL= window.URL.createObjectURL(
        new Blob([blob]))

    so:

    const blobURL= window.URL.createObjectURL(blob);

    reply
    0
  • Cancelreply