Skip to content

Instantly share code, notes, and snippets.

@zahra-ove
Last active March 11, 2022 13:28
Show Gist options
  • Save zahra-ove/82f3bcd7992931001cccb7d2c669914f to your computer and use it in GitHub Desktop.
Save zahra-ove/82f3bcd7992931001cccb7d2c669914f to your computer and use it in GitHub Desktop.
Upload Image via Ajax with FileReader() API
$(document).ready(function(){
$("#subBtn").on('click', function(e) {
e.preventDefault();
let img = $("#pic1")[0].files[0];
let reader = new FileReader();
reader.readAsDataURL(img);
reader.onload = function() {
console.log(reader.result);
sendAjax(reader.result, '/upload');
};
reader.onerror = function() {
console.log(reader.error);
};
});
function sendAjax(data, url)
{
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
data: {data:data},
url: url,
success: function(data) {
console.log('success');
console.log(data);
},
error: function(err) {
console.log('error');
console.log(err);
}
});
}
});
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{csrf_token()}}">
<script src="{{asset('js/jquery-3.6.0.min.js')}}"></script>
<title>Document</title>
</head>
<body>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="pic1" id="pic1" />
<input type="submit" id="subBtn" />
</form>
<script src="{{asset('/js/custom.js')}}"></script>
</body>
</html>
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class UploadController extends Controller
{
public function showForm()
{
return view('fileUpload.uploadForm');
}
public function upload(Request $request)
{
$data = $request->input('data');
$dataImg = $data;
preg_match('#^data:image/(\w+);base64,#i',$data, $matches);
$type = $matches[1];
$dataImg = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $dataImg));
$fileName = 'img_' . time() . '.' . $type;
Storage::disk('public')->put($fileName, $dataImg);
$result = [
'status' => 'success',
'type' => $type,
];
return json_encode($result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment