Skip to content

Instantly share code, notes, and snippets.

@rintoug
Created September 15, 2020 08:35
Show Gist options
  • Save rintoug/2402125e19f0b1248d4cabbc078ef059 to your computer and use it in GitHub Desktop.
Save rintoug/2402125e19f0b1248d4cabbc078ef059 to your computer and use it in GitHub Desktop.
<?php namespace App\Controllers;
class Upload extends BaseController
{
public function index()
{
return view('upload_form');
}
public function doupload()
{
if($files = $this->request->getFiles())
{
foreach($files['files'] as $file)
{
if ($file->isValid() && ! $file->hasMoved())
{
$newName = $file->getName();
$file->move(WRITEPATH.'uploads', $newName);
}
}
print "Files are uploaded";
}
else {
print "There is no files selected";
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to CodeIgniter 4!</title>
<meta name="description" content="The small framework with powerful features">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/png" href="/favicon.ico"/>
<!-- STYLES -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" >
<link href="https://getbootstrap.com/docs/4.5/examples/floating-labels/floating-labels.css" rel="stylesheet">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<!-- CONTENT -->
<main style="width:500px;margin:0 auto;">
<form class="form-signin">
<div id="message"></div>
<div class="text-center mb-4">
<h1 class="h3 mb-3 font-weight-normal">Upload Multiple Files</h1>
<p>This form capable of upload multiple images at once.</p>
</div>
<div class="form-label-group">
<input type="file" id="files" name="files[]" multiple="multiple" >
<label for="inputEmail">Files</label>
</div>
<button class="btn btn-lg btn-primary btn-block" id="upload_btn" type="button">Upload</button>
<p class="mt-5 mb-3 text-muted text-center">© 2017-2020</p>
</form>
</main>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload_btn').on('click', function () {
var formData = new FormData();
var totalFilesLen = document.getElementById('files').files.length;
for (var i = 0; i < totalFilesLen; i++) {
formData.append("files[]", document.getElementById('files').files[i]);
}
$.ajax({
url: 'http://localhost:8888/codeigniter/public/upload/doupload',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (response) {
$('#message').html(response);
},
error: function (response) {
$('#message').html(response);
}
});
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment