Ajax File Upload in Laravel

Ajax File Upload With Form Data Laravel 5.3

Try using the FormData in ajax while you upload a file.

Just try this

$('form').submit(function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '{{ url('/agents') }}',
type: 'POST',
data: formData,
success: function(result)
{
location.reload();
},
error: function(data)
{
console.log(data);
}
});

});

OR

You can try with this jQuery library

https://github.com/malsup/form

EDIT

public function store(Request $request)
{
if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
return $this->respondBadRequest('Phone Number Exists');
}
else
{
$user=User::create($request->all());

if($request->hasFile('image')) {
$file = $request->file('image');

//you also need to keep file extension as well
$name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();

//using the array instead of object
$image['filePath'] = $name;
$file->move(public_path().'/uploads/', $name);
$user->image= public_path().'/uploads/'. $name;
$user->save();
}
return redirect('agents')->with('Success', 'Agent Added');
}
}

Upload a file with Ajax, jQuery and Laravel

Try this:

var formData = new FormData();
var file = $('#file').prop('files')[0];

formData.append('file', file);
formData.append('other_variable', $('#other_variable').val());
// Don't use serialize here, as it is used when we want to send the data of entire form in a query string way and that will not work for file upload

$.ajax({
url: '{{ url("your_url") }}',
method: 'post',
data: formData,
contentType : false,
processData : false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response){
// Do what ever you want to do on sucsess
}
});

In controller method, you will get the file like:

$file = Input::file('file');

how to upload an image via ajax in Laravel 8?

Can you add this line to your header, please!

'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'

  const options = {
method: 'PATCH',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
body: formData,
dataType: 'json', // also tried without
};

I would prefer to set the method to POST.

Laravel upload file using Ajax

You can not upload image using serialize(). you need to use FormData() with these properties;

 contentType: false,
processData: false,
    var data = new FormData($('#addTask_form')[0]);
$.ajax({
url: "{{route('postdataroute')}}",
data: data,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {

}
});
  1. if you don't want to send csrf token

then

    app/Http/Middleware/VerifyCsrfToken.php

and add this route's url to the except array

    protected $except = [
'your route url'
];

  1. if want

then add in head

    <meta name="csrf-token" content="{{ csrf_token() }}">

and in script

    $.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

file upload using ajax in laravel

the # before id is used in jquery but in javascript, you should use just id without #

var pancard = null;
function newfile()
{
pancard = document.getElementById("pancard_image").files[0];
var image_name = pancard.name;
console.log(image_name);
}

How to upload image using ajax in laravel

create.blade.php

@section('content')
<form id="submitform">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name">
</div>

<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="photo" id="photo">
</div>


<button class="btn btn-primary" id="submitBtn" type="submit">
<span class="d-none spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
<span class="">Submit</span>
</button>

</form>
@endsection

@push('custom-scripts')
<script src="{{ asset('js/upload.js') }}"></script>
@endpush

upload.js

$(function () {    
$('#submitBtn').on('click', (e) => {
e.preventDefault();
var formData = new FormData();

let name = $("input[name=name]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
var photo = $('#photo').prop('files')[0];

formData.append('photo', photo);
formData.append('name', name);

$.ajax({
url: 'api/store',
type: 'POST',
contentType: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
data: formData,
success: (response) => {
// success
console.log(response);
},
error: (response) => {
console.log(response);
}
});
});

});

Controller

class MyController extends Controller
{
use StoreImageTrait;

public function store(Request $request)
{
$data = $request->all();
$data['photo'] = $this->verifyAndStoreImage($request, 'photo', 'students');
Student::create($data);
return response($data, 200);
}
}

StoreImageTrait

<?php

namespace App\Traits;

use Illuminate\Http\Request;

trait StoreImageTrait
{

public function verifyAndStoreImage(Request $request, $filename = 'image', $directory = 'unknown')
{
if ($request->hasFile($filename)) {
if (!$request->file($filename)->isValid()) {
flash('Invalid image')->error()->important();
return redirect()->back()->withInput();
}
return $request->file($filename)->store('image/' . $directory, 'public');
}
return null;
}
}



Related Topics



Leave a reply



Submit