大家好,我是 Laravel 和 Reactjs 的新手,我有一个问题,我尝试从服务器下载文件到浏览器。我的请求没问题,但我想要的文件不可读(如果我右键单击浏览器网络->预览,我发现符号和字符不可读),文件也未下载。我使用 Visual Studio Code 在 Windows 中进行编码。
下载控制器:
public function download()
{
$file = public_path()."/file.pdf";
return response()->download($file);
}
Run Code Online (Sandbox Code Playgroud)
路线/api.php:
Route::get('download','Api\DownloadController@download');
Run Code Online (Sandbox Code Playgroud)
在文件Js中:
import React, { Component } from 'react';
import axios from 'axios';
export default class download extends Component{
constructor () {
super();
}
componentDidMount() {
axios.get(`http://127.0.0.1:8000/api/download`)
.then((response) => {
console.log('hello');
});
}
render() {
return (
<div>
<button onClick={this.componentDidMount.bind(this)} className="btn btn-primary">Download</button>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
您必须熟悉 API 使用的 axios 调用,但是如何获取响应文件并将这些文件呈现给用户下载。我们已经为您提供了帮助,下面的代码片段经过测试并且运行良好。
axios({
url: 'http://api.dev/file-download',
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf'); //or any other extension
document.body.appendChild(link);
link.click();
});
Run Code Online (Sandbox Code Playgroud)
感谢 Javilobo 提供的有用解决方案。
您可以查看https://github.com/kenneth Jiang/js- file-download/blob/master/file-download.js 以了解如何处理 IE 下载内容。
更新的解决方案从一开始就在浏览器中显示为下载:
axios({
method: 'post',
url: '/api/download',
data: { itag, url: search, length: size },
responseType: 'arraybuffer',
onDownloadProgress: (progressEvent) => {
let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
setPercentage(percentCompleted);
if (percentCompleted === 100) {
setPercentage(0);
setIsDownloading(false);
}
},
})
.then((response) => {
const blob = new Blob([response.data], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'video.mp4';
a.click();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8369 次 |
| 最近记录: |