搜索

首页  >  问答  >  正文

下载后如何确保文件未损坏?

handleDownload() 函数作为事件处理程序(onclick) 添加到按钮,以便用户可以下载文件。用户可以下载但文件已损坏。我们如何防止文件损坏?

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粉135292805524 天前683

全部回复(1)我来回复

  • P粉384366923

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

    由于您已经收到 Blob 形式的响应,因此无需再次将其转换为 Blob,因此请尝试删除该部分。

    尝试替换:

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

    这样:

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

    回复
    0
  • 取消回复