简体   繁体   English

从服务器下载文件 Laravel 和 reactjs

[英]Download file from the server Laravel and reactjs

Hello everybody I'm new in Laravel and reactjs and I have a question, I try to download file from the server to the browser.大家好,我是 Laravel 和 reactjs 的新手,我有一个问题,我尝试将文件从服务器下载到浏览器。 My request is ok but the file that I wanted is not readable (if I right click on my browser Network->Preview I find symbols and caracters not readable) also the file isn't downloaded.我的请求没问题,但我想要的文件不可读(如果我右键单击我的浏览器网络->预览我发现符号和字符不可读)也没有下载文件。 I used visual studio code for coding in windows.我使用 Visual Studio 代码在 windows 中进行编码。

DownloadController:下载控制器:

public function download()
{
    $file = public_path()."/file.pdf";
    return response()->download($file);
}

routes/api.php:路线/api.php:

Route::get('download','Api\DownloadController@download');

In the file Js:在文件 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>
        );
    }
}

You must be familiar with axios calls for API consumption, but what about getting the files in response and render those files to the user for download.您必须熟悉 axios 调用 API 消耗,但是如何获取文件作为响应并将这些文件呈现给用户以供下载。 We got your covered, the below snippet is tested and works well.我们得到了您的帮助,下面的代码片段已经过测试并且运行良好。

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();
});

Credits to this Javilobo for his useful Solution .感谢这个 Javilobo 的有用解决方案

You can check https://github.com/kennethjiang/js-file-download/blob/master/file-download.js to see how to handle IE download stuff.您可以查看https://github.com/kennethjiang/js-file-download/blob/master/file-download.js了解如何处理 IE 下载内容。

try to set the correct headers in the laravel download function:尝试在 laravel 下载 function 中设置正确的标题:

$headers = [
    'Content-Type' => 'application/pdf',
];

return response()->download($file, 'filename.pdf', $headers);

[1] https://stackoverflow.com/a/20415796/592868 [1] https://stackoverflow.com/a/20415796/592868

You can use header and also conversion before sending contents.您可以使用 header 以及在发送内容之前进行转换。 These line force browser to download a XML file from my custom collection or model.这些行强制浏览器从我的自定义集合或 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;

If your file is ready, no need to read it's content, so you can use this:如果您的文件已准备好,则无需阅读其内容,因此您可以使用它:

return response()->download($pathToFile, $name, $headers);

And $headers can be an array of above example like: $headers可以是上述示例的数组,例如:

$header = ['Content-Type' => 'text/xml'];

with more custom key => value具有更多自定义key => value

There is no need to use Axios or... You can call directly your endpoint URL in your Laravel side, like this in React or pure JS.无需使用 Axios 或...您可以在 Laravel 端直接调用端点 URL,就像在 React 或纯 JS 中一样。

window.location.href = window.YOUR_API_DOWNLOAD_URL;

I know the question is about downloading file from laravel through react as a front end, I am posting for those who are in search to download zip file via react (front end) and laravel (backend).我知道问题是关于通过 react 作为前端从 laravel 下载文件,我为那些正在寻找通过 react(前端)和 laravel(后端)下载 zip 文件的人发布。

First make controller of your choice... add the following function into laravel controller.首先制作您选择的 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));
        }
    }

Now the work of backend is done, in your laravel api route add the below line;现在后端的工作已经完成,在您的 laravel api 路由中添加以下行;

//add it in your routes/api of laravel
Route::get('/zipFileDownload', 'AutosController@downloadZip');

now in react we will work with a file-saver package and fetch request instead of axios.现在在反应中,我们将使用文件保护程序 package 并获取请求而不是 axios。

link: https://www.npmjs.com/package/file-saver链接: https://www.npmjs.com/package/file-saver

Now make any function according to your choice in react, I am assuming functional component so will write method according to functional component syntax.现在根据您在反应中的选择制作任何 function,我假设功能组件,因此将根据功能组件语法编写方法。 note before using saveAs function you need to import from the installed package file-saver.请注意,在使用 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);
              });
}

at the end you need to connect the function with a button with onClick.最后,您需要将 function 与 onClick 的按钮连接起来。 example例子

<button onClick={()=>downloadZipFileFromLaravel()}> </button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM