8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel + Vue のSPAで非同期ファイルダウンロード

Last updated at Posted at 2019-10-06

概要

タイトルの通りです。何だか無駄に考えてしまったので、実装内容おこしておきます。Vueじゃなくてjsとlaravelの話ですが、検索を意識してこのタイトルです。

Laravel 5.6
Vue 2.6
axios 0.19.0

実装

IndexController.php

<?php
namespace App\Http\Controllers\Mlv;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Response;
use Log;

class IndexController extends Controller
{
	public function downLoad(Request $request){
        $ret = [];
		try{
            // ./storage/app/sample.txt をダウンロードする
			$pathToFile = Storage::path("sample.txt");
			return response()->download($pathToFile);
		} catch (\Exception $ex) {
			Log::error($ex->getMessage());
			$ret['status'] = 500; 
			return response()->json($ret, $ret['status']);
		}
	}
}
routes/api.php
Route::get('/download',  'IndexController@downLoad');
vue側
<template>
  <div>
    <v-btn @click="downLoad">download</v-btn>
  </div>
</template>

<script>
export default {
  data() {
  },
  methods: {
    async downLoad(){
      try {
        const res = await axios.get('/api/download')
        if(res.status === 200){
          window.location = res.request.responseURL
        } else {
         // ダウンロード失敗のメッセージって何の飾り気のないalertでも許してもらえる気がする
          alert("downloadに失敗しました")
        }
      } catch(e) {
        alert("downloadに失敗しました")
      }
    }
  }
}
</script>

参考

Fileダウンロード
https://readouble.com/laravel/5.5/ja/responses.html

8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?