登录
首页 >  Golang >  Go问答

浏览器中的文件下载方法

来源:stackoverflow

时间:2024-02-16 17:15:23 398浏览 收藏

哈喽!今天心血来潮给大家带来了《浏览器中的文件下载方法》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我正在开发一个简单的项目,使用 youtube-dl 从浏览器下载视频,以供研究。

我想知道如何使用 axios 在浏览器上下载本地文件(mp4)。浏览器开始下载,但下载完成后,我无法打开 mp4 文件。

这是我的代码片段:

func download(w http.responsewriter, r *http.request) {

    filename := "video.mp4"

    data, err := ioutil.readfile(filename)
    if err != nil {
        log.print(err)
        return
    }

    w.header().set("content-type", "application/octet-stream")
    w.header().set("content-disposition", "attachment; filename="+filename)
    w.header().set("content-transfer-encoding", "binary")
    w.header().set("expires", "0")
    http.servecontent(w, r, filename, time.now(), bytes.newreader(data))
}

这是我的 js 函数,当用户输入文本时触发:

视频文件没有问题,但是当我从浏览器下载它时,无法打开它。

我正在尝试从我的发布请求下载该文件,我应该为其执行单独的获取请求吗?

我的代码有问题,或者我遗漏了什么?


解决方案


问题是axios中处理响应的方法,希望代码可以帮助你

validateGrpc() {
   
    axios.post("http://127.0.0.1:8090/download", {
    data: this.url,
    responseType: 'blob'
  })
          .then(response => {
            var blob = new Blob([response.data]);
            var downloadElement = document.createElement("a");
            var href = window.URL.createObjectURL(blob); //create the download url
            downloadElement.href = href;
            downloadElement.download = "test.mp4"; //the name of the downloaded file
            document.body.appendChild(downloadElement);
            downloadElement.click(); //click to file
            document.body.removeChild(downloadElement); //remove the element 
            window.URL.revokeObjectURL(href); //release the object  of the blob

            //    console.log(response);
          })
          .catch(response => {
            console.log(response);
          });
    },

如果您使用我的代码下载文件,您将从浏览器中看到该文件。 我在github上看到了你的代码。我认为你应该将video.mp4放入目录vue-go-study\backend中。然后一切顺利。

今天关于《浏览器中的文件下载方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>