【问题标题】:Download file from the server Laravel and reactjs从服务器 Laravel 和 reactjs 下载文件
【发布时间】:2020-01-27 13:44:46
【问题描述】:

大家好,我是 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>
        );
    }
}

【问题讨论】:

标签: reactjs laravel


【解决方案1】:

您必须熟悉用于 API 消费的 axios 调用,但是如何获取响应文件并将这些文件呈现给用户以供下载。我们得到了您的保障,下面的 sn-p 已经过测试并且运行良好。

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 有用的Solution

您可以查看https://github.com/kennethjiang/js-file-download/blob/master/file-download.js 了解如何处理 IE 下载内容。

【讨论】:

    【解决方案2】:

    尝试在laravel下载函数中设置正确的headers:

    $headers = [
        'Content-Type' => 'application/pdf',
    ];
    
    return response()->download($file, 'filename.pdf', $headers);
    

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

    【讨论】:

      【解决方案3】:

      您可以在发送内容之前使用标头和转换。这些行强制浏览器从我的自定义集合或模型中下载 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 =&gt; value

      不需要使用 Axios 或 ... 你可以在你的 Laravel 端直接调用你的端点 URL,就像在 React 或纯 JS 中一样。

      window.location.href = window.YOUR_API_DOWNLOAD_URL;
      

      【讨论】:

        猜你喜欢
        • 2020-10-31
        • 2021-09-28
        • 1970-01-01
        • 1970-01-01
        • 2013-08-30
        • 2017-07-06
        相关资源
        最近更新 更多