簡體   English   中英

從服務器下載文件 Laravel 和 reactjs

[英]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);

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

您可以使用 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。

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

現在根據您在反應中的選擇制作任何 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM