后端傳的是二進制流,前端應該如何通過blob處理二進制文件流格式流,並實現前端下載文件流格式


思路:

  1、通過 const blog = new Blob([data.data], { type: 'image/jpeg' }) 獲取blob對象

  2、通過 const url = window.URL.createObjectURL(blog) 獲取blob地址

  3、nodemon 會熱更新,node 改動需要重啟

 

操作步驟:

1、  新建 fileServer 文件夾,在vscode中打開,安裝 express 依賴

npm init -y
npm i express

2、根目錄下新建 public 目錄和 app.js 文件

  public目錄下存放 jpg、word、pdf 文件,做測試用,新建一個index.html

  

  app.js:

const express = require('express') // npm i express
const app = express()
const path = require('path')

app.use(express.static(path.join(__dirname, 'public'))) // http://localhost:3001/img01.jpg  可以訪問到這張圖片

app.get('/test', (req, res) => {
  res.send('ok222222') // http://localhost:3001/test  可以訪問到輸出內容
})

app.listen(3001, () => {
  console.log('啟動服務器')
})

  此時,終端執行 nodemon app.js,(前提是已經提前安裝nodemon:npm i nodemon -g)然后訪問 http://localhost:3001/test 可以打印 “ok222222”,訪問 http://localhost:3001/img01.jpg 可以預覽 public 中的圖片,同樣的,http://localhost:3001/index.html 可以訪問到頁面

3、創建接口

    const express = require('express') // npm i express
    const app = express()
    const path = require('path')

    const imgPath = path.join(__dirname, 'public', 'img01.jpg')
    const wordPath = path.join(__dirname, 'public', 'word.docx')
    const pdfPath = path.join(__dirname, 'public', 'test.pdf')
    console.log(imgPath) // D:\desktop\fileServer\public\img01.jpg
    app.use(express.static(path.join(__dirname, 'public'))) // http://localhost:3001/img01.jpg  可以訪問到這張圖片

    app.get('/test', (req, res) => {
      res.send('ok222222') // http://localhost:3001/test  可以訪問到輸出內容
    })

    // 提供img下載接口
    app.get('/saveImg', (req, res) => {
      res.download(imgPath)
    })

    // 提供img預覽接口
    app.get('/showImg', (req, res) => {
      res.sendFile(imgPath)
    })

    // 提供word下載接口  sendFile和download都是下載
    app.get('/saveWord', (req, res) => {
      res.sendFile(wordPath)
    })

    // 提供pdf預覽接口  訪問控制台打印的地址時sendFile和download都是預覽,用a標簽訪問時都是下載
    app.get('/showPdf', (req, res) => {
      res.sendFile(pdfPath)
    })

    app.listen(3001, () => {
      console.log('啟動服務器')
    })

    /*
      nodemon會熱更新,node需要重啟
    */

4、index.html 中點擊按鈕拿到接口返回的值    常見 MIME 類型列表

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button onclick="handleDownload()">獲取img地址</button>
  <br>
  <a href="http://localhost:3001/saveImg">下載img</a>
  <br>
  <a href="http://localhost:3001/showImg" target="_blank">打開img</a>
  <br>
  <button onclick="handleDownload1()">獲取word地址</button>
  <br>
  <a href="http://localhost:3001/saveWord">下載word</a>
  <br>
  <button onclick="handleDownload2()">獲取pdf地址</button>
  <br><a href="http://localhost:3001/showPdf">下載pdf</a>
  <br>
</body>

</html>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  function handleDownload() {
    axios({
      url: 'http://localhost:3001/saveImg',
      responseType: 'blob',
      method: 'get'
    })
      .then(data => {
        console.log(data)
        const blog = new Blob([data.data], {
          type: 'image/jpeg'
        }) // 將data數據轉為blob對象
        const url = window.URL.createObjectURL(blog) // 將blob對象轉為blob地址
        console.log(url)
        // 創建DOM實現下載
        // let a = document.createElement('a')
        // a.download = 'img01.jpg'
        // a.href = url
        // a.click()
      }).catch(err => {
        console.error(err)
      })
  }
  function handleDownload1() {
    axios({
      url: 'http://localhost:3001/saveWord',
      responseType: 'blob',
      method: 'get'
    })
      .then(data => {
        console.log(data)
        const blog = new Blob([data.data], {
          // type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
          type: 'application/msword'
        })
        const url = window.URL.createObjectURL(blog)
        console.log(url)
      }).catch(err => {
        console.error(err)
      })
  }
  function handleDownload2() {
    axios({
      url: 'http://localhost:3001/showPdf',
      responseType: 'blob',
      method: 'get'
    })
      .then(data => {
        console.log(data)
        const blog = new Blob([data.data], {
          type: 'application/pdf'
        })
        const url = window.URL.createObjectURL(blog)
        console.log(url)
      }).catch(err => {
        console.error(err)
      })
  }
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM