<input class="form-control" type="file" id="pro-image" name="image[]" multiple>
When Id work Successfully this time Name does not catch image path.
That means empty Array.
But when remove Id just use name="image[]" successfully submit value.
Assuming you have a form, you can submit the images via Ajax using the fetch API like so
<form action="/" method="post" enctype="multipart/form-data">
#csrf
<input class="form-control" type="file" id="pro-image" name="image[]" multiple>
<button type="submit">Submit</button>
</form>
<script>
let form = document.forms[0];
form.onsubmit = (event) => {
event.preventDefault();
fetch('/', {
method: 'POST',
credentials: "same-origin",
body: new FormData(form),
});
}
</script>
And return the paths array for the images like so
Route::post('/', function () {
$images = request()->file('image');
$paths = [];
foreach ($images as $image) {
$paths[] = $image->store('/public');
}
return $paths;
});
And without a form, listen to input change
<meta name="csrf-token" content="{{ csrf_token() }}">
<input class="form-control" type="file" id="pro-image" name="image[]" multiple onchange="submit()">
<script>
function submit() {
var ins = document.getElementById('pro-image').files.length;
var fd = new FormData();
for (var x = 0; x < ins; x++) {
fd.append("pro-image[]", document.getElementById('pro-image').files[x]);
}
fetch('/', {
headers: {
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content
},
method: 'POST',
credentials: "same-origin",
body: fd,
});
}
</script>
And access from backend
Route::post('/', function () {
$images = request()->file('pro-image');
$paths = [];
foreach ($images as $image) {
$paths[] = $image->store('/public');
}
return $paths;
});
Now you can see paths of the stored images in public directory on the network tab of dev tools
Hope this helps
Related
Hi has anyone tried to use FilePond with Laravel to upload files in chunks ?
I am trying to do that but I dont know how to get the content of a PATCH method.
The upload starts, and a receive a bunch of PATCH methods, I see (Network Tab in Dev Mode Firefox) that they are different, because the offset changes.
Let me know if you need more details to help me.
My blade view (where the js is located):
<form action="{{ route('upload.store') }}" enctype="multipart/form-data"
method="post">
#csrf
<input class="" id="imageUploadFilePond" name="file" type="file">
<button class="btn btn-primary" type="submit">Submit</button>
</form>
#push('scripts')
<script src="https://unpkg.com/filepond#^4/dist/filepond.js"></script>
<script>
const inputElement = document.querySelector('#imageUploadFilePond');
const pond = FilePond.create(inputElement, {
server: {
url: '/upload',
patch: "/",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
},
chunkUploads: true,
chunkSize: 1048576,
chunkForce: true,
});
</script>
#endpush
In my UploadController.php my methods :
public function store(Request $request)
{
if ($request->file === '{}') {
return uniqid();
}
return '';
}
public function update(Request $request, $id)
{
$uploadOffset = $request->header('upload-offset');
$uploadLenght = $request->header('upload-length');
$uploadName = $request->header('upload-name');
$numberOfChunks = $uploadLenght / self::CHUNKSIZE;
$currentChunk = $uploadOffset / self::CHUNKSIZE;
return $id;
}
I am using Axios for uploading images.
Here is my HTML:
<form action="" method="post">
<input type="text" id="name">
<input type="files" multiple id="file">
<button type="submit" onclick="submit_form()">Upload</button>
</form>
Axios code:
function submit_form(e) {
e.preventDefault();
var form = new FormData();
var name = document.getElementById("name").value;
var image = document.getElementById("file");
for (i = 0; i < image.files.length; i++) {
let file = image.files[i];
form.append("files[" + i + "]", file);
}
form.append("name", name);
axios.post("ajax.php", form, {headers: {'content-type': 'multipart/form-data'}})
.then((r) => {
console.log(r);
})
}
ajax.php:
$data = json_decode(file_get_contents("php://input"), true);
echo json_encode($data);
In the console it shows me null
If my PHP code is wrong, then can someone give a simple example?
view:
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
product_name = $("#product_name").val();
color = $("#colorWell").val();
$.ajax({
type:"POST",
data:{"product_name":product_name, "color":color},
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
alert(data);
}
});
});
});
</script>
<input type="text" class="form-control" id="product_name" name="product_name">
<input type="color" id="colorWell" name="color">
<input type="file" id="product_image" name="product_image[]" multiple>
<input type="submit" class="btn btn-primary" id="submit" name="submit">
controller:
public function products()
{
$product_name = $this->input->post('product_name');
$color = $this->input->post('color');
$dataInfo = array();
$files = $_FILES;
$cpt = count($_FILES['product_image']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['product_image']['name']= $files['product_image']['name'][$i];
$_FILES['product_image']['type']= $files['product_image']['type'][$i];
$_FILES['product_image']['tmp_name']= $files['product_image']['tmp_name'][$i];
$_FILES['product_image']['error']= $files['product_image']['error'][$i];
$_FILES['product_image']['size']= $files['product_image']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$dataInfo[] = $this->upload->data();
}
$data = array(
'product_name' => $product_name,
'color' => $color,
'product_image' => implode(",",$dataInfo['product_image']),
);
$result_set = $this->db->insert('add_product',$data);
if($sql == true)
{
echo 'New Product Added';
}
else
{
echo 'Unable to Proceed!';
}
}
private function set_upload_options()
{
$config = array();
$config['upload_path'] = ''.base_url().'resource/product/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
In this code I am trying to insert and wants to move an image into a folder. But Now, problem is that when I click on submit button it throw an error as show in below:
Message: Undefined index: product_image
and query looks:
INSERT INTO `product` (`product_name`, `color`, `product_image`) VALUES ('men hoodies','#004080', NULL)
I don't know where am I doing wrong. So, How can I solve this issue? Please help me.
Thank You
Send all formdata with file in your ajax.
HTML code like this...
<form method="POST" id="YourFormID" enctype="multipart/form-data">
<input type="text" class="form-control" id="product_name" name="product_name">
<input type="color" id="colorWell" name="color">
<input type="file" id="product_image" name="product_image[]" multiple>
<input type="submit" class="btn btn-primary" id="submit" name="submit">
</form>
Ajax code here....
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var formData = new FormData($('form#YourFormID')[0]);
$.ajax({
type:"POST",
data:formData,
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
alert(data);
}
});
});
});
</script>
You are not send file in your ajax request. therefore not found index product_image
You didn't submit the files data.
Use formData to upload files data, and append any other input you like to add to formData :
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
product_name = $("#product_name").val();
color = $("#colorWell").val();
var formData = new FormData();
$.each($("#product_image"), function (i, obj) {
$.each(obj.files, function (j, file) {
formData.append('product_image[' + i + ']', file);
});
});
formData.append('product_name', product_name);
formData.append('color', color);
$.ajax({
type:"POST",
data:formData,
processData: false,
contentType: false,
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
alert(data);
}
});
});
});
</script>
use array_column like below to add get all product_image values
implode(",",array_column($dataInfo, 'product_image'))
I started learning laravel, and attempt to make a website with it. I'm trying implement "uploading a crop image". I'm using croppie https://foliotek.github.io/Croppie/ and manage to successfully displaying on the browser.
Now, I want to save the image to the database. I'm struggling at this stage, I've spent hours searching and trying but it doesn't seem to work. I've read that laravel doesn't use the patch method to send crop images as well as I need ajax. Can someone help me how I would get the base64 from the form. This is my form:
<form action="{{route('program.updateImage', ['id'=> $program->id])}}" method="post" enctype="multipart/form-data">
{{ method_field('PATCH') }}
{{ csrf_field() }}
<div id="crop" class="croppie-container">
</div>
<a class="upload-file">
<span>Upload</span>
<input type="file" name="image" id="upload"><br>
</a>
<br>
<input type="submit" name="submit" value="Save image">
</form>
This is my route:
Route::patch('program/image/{id}', 'ProgramController#updateImage')->name('program.update');
Code for croppie
$(function() {
var basic = $('#crop').croppie({
viewport: {
width: 400,
height: 200
},
boundary: { width: 400, height: 300 },
});
basic.croppie('bind', {
url: '{{asset('images/'.$program->image)}}'
});
});
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#crop').croppie('bind', {
url: e.target.result
});
}
reader.readAsDataURL(input.files[0]);
}
}
$('.upload-file input').on('change',function(){
readFile(this);
});
and my function:
public function updateImage(Request $request, $id){
//$this->validate($request, array('image' => 'mimes:jpeg,jpg,png'));
$program = Program::find($id);
//list($type, $data) = explode(';', $data);
//list(, $data) = explode(',', $data);
//$data = base64_decode($data);
echo $request;
}
Here jquery code for upload image
$('#crop_img_upload_button').on('click', function (e) {
var image_data = $('#crop').croppie('result', 'base64');
if (image_data != '') {
var formData = $('#crop_it_form').serialize();
$.ajax({
type: "POST",
url: "uploadUrl",
data: formData,
cache: false,
success: function (data)
{
//response here
}
});
} else {
// validation msg here
}
});
});
To get base64 of image use this :
var base64 = $('#crop').croppie('result', 'base64');
I've create one form which is given below
html code:
<form method="post" class="inline" id="upload_form" enctype="multipart/form-data">
<input style="margin-top:0px;" type="file" name="data1" id="file1" class="btn btn-block btn-primary"/>
<input type="hidden" name="_token" value="{{ csrf_token() }}" id="token">
link submit
</form>
ajax code:
function create()
{
alert();
var file = document.getElementById('file1');
var token = document.getElementById('token').value;
var data1 = new FormData($("#upload_form")[0]);
var route = "http://localhost:8080/form";
console.log(FormData);
console.log(data1);
$.ajax({
type:'POST',
url: route,
headers: {'X-CSRF-TOKEN': token},
contentType: false,
processData: false,
data:{
'data1': data1,
},
success:function(e){
if(e == 0)
{
alert("Success Full Created");
}
else
{
alert("Error");
}
}
});
}
This is my route :
Route::post('form', 'StoreController#newstore');
I've created controller which is given below
Controller :
public function newstore(Request $request)
{
$post = $request->file('data1');
dd($post);
//If there is error try dd($post) and let me know
// we need know if the data file image is passing to controller
$imageName = $post->getClientOriginalName();
$imagemove= $post->move(public_path('images'),$imageName);
$data123 = array ( "photo"=> $imageName, );
$check222 = DB::table('product') -> insert($data123);
}
when i run this code its show me this error :
MethodNotAllowedHttpException in RouteCollection.php line 218:
Try this:
<form method="post" class="inline" id="upload_form" enctype="multipart/form-data">
<input style="margin-top:0px;" type="file" name="data1" id="file1" class="btn btn-block btn-primary"/>
<input type="hidden" name="_token" value="{{ csrf_token() }}" id="token">
link submit
</form>
if for example your route is:
Route::post('form', 'yourcontroller#newstore');
JS
function create()
{
var file = document.getElementById('file1');
var route = "http://localhost:8000/form";
var token = document.getElementById('token').value;
var data1 = new FormData($("#upload_form")[0]);
// we are using "$", i hope that you have jquery library
/* alternative you can do:
var getUpload = document.queryselector('#upload_form');
var data1 = getUpload[0];
*/
//if there is error try also console.log(formData)
// if error try console-log(data1); info about the file uploaded
// if error token verify console.log(token); have the token serial number
$.ajax({
type:'POST',
url: route,
headers: {'X-CSRF-TOKEN': token},
contentType: false,
processData: false,
data:{
'data1': data1,
},
success:function(e){
if(e == 0)
{
alert("Success Full Created");
}
else
{
alert("Error");
}
}
});}
var submit = document.querySelector('#submit').onclick= create
CONTROLLER
public function newstore(Request $request)
{
$post = $request->file('data1');
//If there is error try dd($post) and let me know
// we need know if the data file image is passing to controller
$imageName = $post->getClientOriginalName();
$imagemove= $post->move(public_path('images'),$imageName);
$data123 = array ( "photo"=> $imageName, );
$check222 = DB::table('product') -> insert($data123);
}
Let me know if you get some error! i hope it work!