typescript 来自Laravel API的Angular下载文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 来自Laravel API的Angular下载文件相关的知识,希望对你有一定的参考价值。

<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use Spatie\MediaLibrary\Media;

class DownloadController extends ApiController
{

    public function __construct()
    {

    }

    /**
     * Download media based on media id
     * @param Request $request
     * @param $media_id
     * @return Media
     */
    public function downloadMedia(Request $request, $media_id)
    {
        $media = Media::findOrFail($media_id);

        return $media;
    }
}
// download API in routes/api.php

$api->get('media/{media_id}/download','DownloadController@downloadMedia');
<table class="table">
    <tbody>
        <tr *ngFor="let file of uploaded_files">
            <td>{{ file.name }}</td>
            <td>
                <button type="button" class="btn btn-primary btn-sm pull-right"
                    aria-label="Close" (click)="downloadFileService.downloadFile(file)">
                    <i class="fa fa-download"></i>
                </button>
            </td>
        </tr>
    </tbody>
</table>
@Component({
    templateUrl: './relocation-view.component.html',
    styleUrls: ['./relocation.component.scss']
})
export class RelocationViewComponent extends Component implements OnInit, OnDestroy {
  
    uploaded_files: File[] = [];

    constructor(
        public downloadFileService: DownloadFileService
    ) {
        
    }
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import saveAs from 'file-saver';

@Injectable()
export class DownloadFileService {

    private static base_url: string = '';

    constructor(
      private http: HttpClient
    ) {
        
    }

    downloadFile(file: any) {

        const url = DownloadFileService.base_url + '/' + file.id + '/download';

        const response_file = this
            .http
            .get(url, { responseType: 'blob' })
            .subscribe(
            res => {
                saveAs(res, file.name);
            }
        );

        return response_file;
    }
}

以上是关于typescript 来自Laravel API的Angular下载文件的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 5.7 处理来自 API 的电子邮件验证错误

如何调试来自 ReactJs(另一个项目)客户端的 Laravel API 请求?

来自 laravel api 的外部 phpmyadmin

验证来自 laravel 8 api 中两个以上表的用户

来自 laravel 会话登录的经过身份验证的 api 调用。可能吗?

来自 Vue.js 的 Laravel API 调用导致 GET 路由的 CORS