Laravel

API 비동기로 파일 다운 구현하는법

짱구를왜말려? 2022. 3. 29. 21:43
반응형
SMALL

# What?

비동기 통신으로 파일 다운로드 구현

 

# Why?

api는 비동기 통신 기반이라 일반적인 방법으로 파일 다운 불가능, 그렇다고 web.php 따로 뚫으면 보안 취약 및 불편

 

# How?

-> 파일 저장

-> 저장된 파일 url을 리턴

-> 프론트단에서 a태그에 해당 링크를 연결 후 클릭 이벤트 발생시키기

 

@ 백엔드

    public function download(Request $request)
    {
        ...

        $download = Download::create();

        $path = $download->id."/".$request->order.'주차 과제기록.xlsx';

        Excel::store(new UsersExport($request->target_ids, $request->order, $request->includes), $path , "s3");

        $url = Storage::disk("s3")->url($path);

        return $this->respondSuccessfully($url);
    }

 

@ 프론트

    download() {
           this.form.post("/api/users/download")
                .then(response => {
                    let a = document.getElementById("download");

                    a.href = response.data.data;

                    a.click();
                })
        },
LIST