【问题标题】:vue client file direct download from node js server doesnt workvue客户端文件直接从节点js服务器下载不起作用
【发布时间】:2020-04-07 01:30:04
【问题描述】:

好的,所以我已经尝试了 2 天,在 http 请求(使用 axios)。

堆栈溢出中有一些关于此的主题,但它们都没有解决我的问题,我可能在某个地方犯了错误,但我似乎无法看到确切的位置。

我的浏览器/客户端收到响应,但没有将其转换为直接下载,如下所示:

{data: "ID3#TSSELavf57.71.100���…UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {url: "http://localhost:8081/api/tracks/download/5df305bc6cea85c8eac5d3e6", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}
data: "ID3#TSSELavf57.71.100���..."
headers: {cache-control: "public, max-age=0", content-length: "9775064", content-type: "audio/mpeg", last-modified: "Fri, 13 Dec 2019 03:30:04 GMT"}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
status: 200
statusText: "OK"
__proto__: Object

我是否需要设置代理,我不确定我是否完全理解如何正确执行此操作?我真的一直在努力让它发挥作用,哈哈

代码如下:

node.js 服务器下载路径

router.get('/download/:id', async (req, res) => {
  const tracks = await loadTracksCollection();
  var id = new mongodb.ObjectID(req.params.id);
  var track = await tracks.findOne({ _id: id });
  var trackPath = String(track.path);
  var trackName = String(track.user + ' - ' + track.name + '.mp3');
  res.download(trackPath, trackName, (err) => {
    if (err) {
      console.error(err);
      return ;
    } else {
    tracks.updateOne({ _id: id }, { $inc: { downloadCount: 1 } });
    // return res.status(200).send('The download should start ...')
    }
  });
});

vue.js 按钮组件

<template>
  <v-btn @click="download" depressed block color="accent"><unicon name="import" fill="white" /></v-btn>
</template>

<script>
import axios from 'axios'

export default {
  props: {
    fileId: {
      required: true,
      type: String
    }
  },
  methods: {
    download() {
      axios.get(process.env.VUE_APP_AUDIO_API_URL + '/api/tracks/download/' + this.fileId)
           .then(response => {
             console.log(response)
           })
           .catch(error => {
             console.error(error)
           })
    }
  }
}
</script>

如果需要更多代码,请告诉我!

非常感谢!

【问题讨论】:

    标签: javascript node.js vue.js axios


    【解决方案1】:

    需要在axios中更改responseType...

    axios({
        method: 'GET',
        url: process.env.VUE_APP_AUDIO_API_URL + '/api/tracks/download/' + this.fileId,
        responseType: 'arraybuffer'
    }).then(response => {
       console.log(response.data)
    }).catch(error => {
       console.error(error)
    })
    

    【讨论】:

    • 您好,感谢您回答我!刚试过这个,开发工具现在控制台:ArrayBuffer(440651) {} ...(有一堆 int 数组)但没有直接下载发生
    【解决方案2】:

    好吧,这似乎是一个复杂的主题,但我找到了我的解决方案:

          this.$axios({
              method: 'GET',
              url: // ur backend api url,
              responseType: 'arraybuffer'
            })
            .then(response => {
              var blob = new Blob([response.data], {type: response.headers['content-type']})
              var link = document.createElement('a')
              link.href = window.URL.createObjectURL(blob)
              link.download = // name the downloaded file
              link.click()
            })
            .catch(error => { 
              // whatever
            })
            .finally(() => {
              // whatever
            }
    
    

    【讨论】:

      猜你喜欢
      • 2011-08-15
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 2015-12-05
      • 1970-01-01
      • 2021-02-20
      相关资源
      最近更新 更多