Create websites with TailwindCSS
Start building the next great SAAS
Alpine & Tailwind UI Library
Plug'n Play Authentication for Laravel
Create website designs with AI
Blog platform for developers
Build a simple static website
21-day program to build a SAAS
Created on December 27th, 2015
Learn how to upload multiple files with Laravel. It's actually fairly simple and in this video we'll walk you through step-by-step on how to perform this functionality.
Below you can find the code to the view, route file, and the controller.
view file (inside body tags of welcome.blade.php)
<form action="upload" id="upload" enctype="multipart/form-data">
<input type="file" name="file[]" multiple><br />
<input type="submit">
</form>
<div id="message"></div>
<script>
var form = document.getElementById('upload');
var request = new XMLHttpRequest();
form.addEventListener('submit', function(e){
e.preventDefault();
var formdata = new FormData(form);
request.open('post', '/upload');
request.addEventListener("load", transferComplete);
request.send(formdata);
});
function transferComplete(data){
response = JSON.parse(data.currentTarget.response);
if(response.success){
document.getElementById('message').innerHTML = "Successfully Uploaded Files!";
}
}
</script>
route file (upload route in routes.php)
Route::post('upload', 'UploadController@upload');
controller file (UploadController.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Storage;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UploadController extends Controller
{
//
public function upload(Request $request){
$files = $request->file('file');
if(!empty($files)):
foreach($files as $file):
Storage::put($file->getClientOriginalName(), file_get_contents($file));
endforeach;
endif;
return \Response::json(array('success' => true));
}
}
Hope this will help you in your future projects :) Please feel free to post any comments or questions below. Thanks.
Comments (0)