[英]Download file from the server Laravel and reactjs
大家好,我是 Laravel 和 reactjs 的新手,我有一个问题,我尝试将文件从服务器下载到浏览器。 我的请求没问题,但我想要的文件不可读(如果我右键单击我的浏览器网络->预览我发现符号和字符不可读)也没有下载文件。 我使用 Visual Studio 代码在 windows 中进行编码。
下载控制器:
public function download()
{
$file = public_path()."/file.pdf";
return response()->download($file);
}
路线/api.php:
Route::get('download','Api\DownloadController@download');
在文件 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>
);
}
}
您必须熟悉 axios 调用 API 消耗,但是如何获取文件作为响应并将这些文件呈现给用户以供下载。 我们得到了您的帮助,下面的代码片段已经过测试并且运行良好。
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();
});
感谢这个 Javilobo 的有用解决方案。
您可以查看https://github.com/kennethjiang/js-file-download/blob/master/file-download.js了解如何处理 IE 下载内容。
尝试在 laravel 下载 function 中设置正确的标题:
$headers = [
'Content-Type' => 'application/pdf',
];
return response()->download($file, 'filename.pdf', $headers);
您可以使用 header 以及在发送内容之前进行转换。 这些行强制浏览器从我的自定义集合或 model 下载 XML 文件。
$response = Response::create(strval($someCollection), 200);
$response->header('Content-Type', 'text/xml');
$response->header('Cache-Control', 'public');
$response->header('Content-Description', 'File Transfer');
$response->header('Content-Disposition', 'attachment; filename=custome_filename.xml');
$response->header('Content-Transfer-Encoding', 'binary');
return $response;
如果您的文件已准备好,则无需阅读其内容,因此您可以使用它:
return response()->download($pathToFile, $name, $headers);
$headers
可以是上述示例的数组,例如:
$header = ['Content-Type' => 'text/xml'];
具有更多自定义key => value
无需使用 Axios 或...您可以在 Laravel 端直接调用端点 URL,就像在 React 或纯 JS 中一样。
window.location.href = window.YOUR_API_DOWNLOAD_URL;
我知道问题是关于通过 react 作为前端从 laravel 下载文件,我为那些正在寻找通过 react(前端)和 laravel(后端)下载 zip 文件的人发布。
首先制作您选择的 controller... 将以下 function 添加到 laravel Z594C103F2C6E04C3CDAZ059031E 中。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
use ZipArchive;
class ZipController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function downloadZip()
{
$zip = new ZipArchive;
$fileName = 'myNewFile.zip';
if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE)
{
$files = File::files(public_path('myFiles')); //note that this location or folder must exists in order to make the zip file.
foreach ($files as $key => $value) {
$relativeNameInZipFile = basename($value);
$zip->addFile($value, $relativeNameInZipFile);
}
$zip->close();
}
return response()->download(public_path($fileName));
}
}
现在后端的工作已经完成,在您的 laravel api 路由中添加以下行;
//add it in your routes/api of laravel
Route::get('/zipFileDownload', 'AutosController@downloadZip');
现在在反应中,我们将使用文件保护程序 package 并获取请求而不是 axios。
现在根据您在反应中的选择制作任何 function,我假设功能组件,因此将根据功能组件语法编写方法。 请注意,在使用 saveAs function 之前,您需要从已安装的 package 文件保护程序中导入。
import { saveAs } from 'file-saver';
const downloadZipFileFromLaravel=()=>{
fetch(`your url/zipFileDownload`)
.then(res => res.blob())
.then(blob => saveAs(blob, 'Auto Photos.zip')) // saveAs is a function from the file-saver package.
.catch((err) => {
console.log(err.message);
});
}
最后,您需要将 function 与 onClick 的按钮连接起来。 例子
<button onClick={()=>downloadZipFileFromLaravel()}> </button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.