gpt4 book ai didi

javascript - 如何在浏览器上下载文件

转载 作者:行者123 更新时间:2023-12-01 22:20:30 26 4
gpt4 key购买 nike

我正在做一个简单的项目,目的是使用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函数,当用户输入文本时触发:
<script>
import axios from 'axios';

export default {
name: 'govideo',

data() { return {
url: '',
} },

methods: {
postreq() {
axios.post("http://127.0.0.1:8090/download", {
data: this.url,
responseType: 'blob'
}).then((response) => {
var fileURL = window.URL.createObjectURL(new Blob([response.data]));
var fileLink = document.createElement('a');

fileLink.href = fileURL;
fileLink.setAttribute('download', 'video.mp4');
document.body.appendChild(fileLink);

fileLink.click();
})
}
}
}
</script>
视频文件没有问题,但是当我从浏览器下载它时,无法打开它。
我正在尝试从发帖请求中下载文件,我是否应该对此做一个单独的获取请求?
我的代码有什么问题,或者我错过了什么?

最佳答案

问题是在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目录中,然后一切顺利。

关于javascript - 如何在浏览器上下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63858284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com