LoginSignup
5
9

More than 5 years have passed since last update.

ajax axiosでファイル保存

Last updated at Posted at 2018-12-29

ボタン押下から(ファイル選択ダイアログ)が開きます。
ファイル選択ボタン押下で、自動的に指定画像ディレクトリにファイルが書き込まれます。
自動的に書き込む際に、ajaxとlaravelを使用します。

<button type="button" class="btn btn-sm btn-primary mr-2" @click="mdInpAux_img">画像アップロード</button>

<form class="d-none" action="{{ route('upload') }}" method="post" enctype="multipart/form-data" id="imgUploadForm">
  @csrf
    <input type="file" class="btn btn-sm btn-primary" ref="img_inp" name="upload_img" @change="upload">
</form>
//vuejs.methods
mdInpAux_img: function() {
  this.$refs.img_inp.value = null;
  多分これで画像選択ダイアログキャンセル時にinput:fileのchangeイベントが発生しないようになっていると思います
  this.$refs.img_inp.click();
},
upload: function(e) {
  var formData = new FormData();
  formData.append("image", this.$refs.img_inp.files[0]);
  axios.post('/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(function(response) {
    console.log(response);
  })
  .catch(function(error) {
     console.log(error);
  });
}
//routes.web.php
Route::post('/upload', 'ImagesController@upload')->name('upload');

laravelでのファイルアップロード方法について、参考にさせて頂きました。
ありがとうございます。
参考記事

//ImagesController
<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class ImagesController extends Controller {
  public function upload(Request $request) {
    $name = $request->image->getClientOriginalName();//ファイル名を取得します。
    $request->image->storeAs('images', $name);//storeメソッドだとファイル名がハッシュ化されるため、storeAsを使用。

    return response()->json([
      'result' => 'success',
    ]);
  }
}
5
9
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
5
9