我正在做一个简单的项目,使用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>视频文件没有问题,但当我从浏览器下载时,我无法打开它。
我正在尝试从post请求中下载文件,我应该为它做一个单独的get请求吗?
是我的代码有问题,还是我遗漏了什么?
发布于 2020-09-12 17:17:00
问题是在axios.I中处理响应的方法。我希望代码能对你有所帮助
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.I上的代码了,我想你应该把video.mp4放到vue-go-study\backend.Then目录下,一切都很顺利。
https://stackoverflow.com/questions/63858284
复制相似问题