@darrion.kuhn
To upload an image using AJAX in Laravel, you can follow the steps below:
- Create a form in your view file to select the image file:
1
2
3
4
5
|
<form method="POST" enctype="multipart/form-data" id="imageForm">
@csrf
<input type="file" name="image" id="image">
<button type="submit">Upload Image</button>
</form>
|
- Create a script in your view file to handle the AJAX request and submit the form data:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<script>
$(document).ready(function () {
$('#imageForm').submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
// do something with the response
}
});
});
});
</script>
|
- Create a route in your web.php file to handle the AJAX request:
1
|
Route::post('/upload', 'ImageController@upload');
|
- Create a controller named ImageController with a method upload to handle the file upload:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
namespace AppHttpControllers;
use IlluminateHttpRequest;
class ImageController extends Controller
{
public function upload(Request $request) {
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $imageName);
return response()->json(['success'=>'Image uploaded successfully']);
}
}
|
- Make sure you have a folder named images in your public directory where the uploaded images will be stored.
- That's it! Now you should be able to upload an image using AJAX in Laravel.