HTML anchor tag download attribute not working in Firefox for jpg and png files

前端 未结 3 1648
感动是毒
感动是毒 2021-01-04 07:03

In my web application I have supported user to upload any type of document (.png, .jpg, .docx, .xls, ... )
I\'m trying to implement download functionality for these do

3条回答
  •  粉色の甜心
    2021-01-04 07:47

    I had a similar problem with firefox not handling the download attribute, even for same-domain files.

    My target files are actually hosted on AWS, so they are cross-domain. I got around this with a same-domain endpoint that downloads the remote file and pipes it to the client.

    const express = require('express')
    const {createWriteStream} = require('fs')
    const downloadVideo = (url) => { return new Promise((resolve, reject) => {
      const filePath = `/tmp/neat.mp4`
      const ws = createWriteStream(filePath)
      request(url, {}, (error, response, body) => {
        if(error) { return reject(error) }
        resolve(filePath)
      }).pipe(ws)
    })}
    
    app.get('/api/download', async (req, res) => {
      const videoPath = await downloadVideo(req.query.url)
      res.sendFile(videoPath)
    })
    

    On the client, I send the file path to the download endpoint to get a blob back, which is then converted to an object url. From there, it's standard download attribute stuff.

    async download(remoteFilePath){
      const a = document.createElement('a')
      const dlURL = `/api/download?url=${encodeURIComponent(remoteFilePath)}`
      const blob = await fetch(dlURL).then(res => res.blob())
      a.href = URL.createObjectURL(blob)
      a.setAttribute('download', 'cool.mp4')
      document.body.appendChild(a)
      a.click()
      a.remove()
    }
    

提交回复
热议问题