Uploading multiple images with dropzone.js with Laravel - php

I am using dropzone with laravel to upload multiple images and it works correctly. what I am asking for is I want to upload them at once and then send email to my customer to show him that photos have been uploaded.
Thanks in advance.
<form action="{{route('upload.photos')}}" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneFileUpload" >
{{csrf_field()}}
<div>
<h3 class="text-center">Upload Multiple Image By Click On Box</h3>
</div>
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize:500,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 25,
maxFiles: 25
};
</script>
$file = $request->file('file');
$fileName = time().$file->getClientOriginalName();
Storage::disk('local')->put($car_id.'/'.$fileName, File::get($file));
Photo::create([
'photo_name'=>$fileName,
'car_id'=>$car_id
]);
$data = [
'first_name'=>$car->user->first_name,
'last_name'=>$car->user->last_name,
'vin'=>$car->vin,
'model'=>$car->model,
'make' =>$car->make
];
Mail::send('admin.email.send_album_notification',$data,function($message) use($car){
$message->subject('Pictures for Test - Example ');
$message->from('noreply#example .com','Example ');
$message->to($car->user->email,$car->user->full_name);
});

If I share my experience then Create one unique id for every form like
<form>
<input type="hidden" value="{{ uniqid() .'-'. Carbon\Carbon::now()->timestamp }}" name="form-token"/>
<form>
Now you have identification for every form right. Insert it with every image. It is very easy to track every image.
For Example:
Photo::create([
'photo_name'=>$fileName,
'car_id'=>$car_id,
'form_token'=>$request->get('form-token'),
]);
Once you insert that You have form_token column to find all uploaded image at a time. Mean to say suppose your user uploaded 5 images and each image have same token. Now just find that images by token and send into mail.
$photos = Photo::whereFormToken($request->get('form-token'))->get();
$data['photos'] = $photos;
Mail::send('admin.email.send_album_notification',$data,function($message) use($car){
$message->subject('Pictures for Test - Example ');
$message->from('noreply#example .com','Example ');
$message->to($car->user->email,$car->user->full_name);
});
Now your mail view file have photos collection object so you can just print out it. Something like this:
#foreach($photos as $photo_key => $photo_value)
<?php $pathToImage = public_path()."/".$photo_value->image_name; ?>
<img src="{!! $photo_value->embed($pathToImage); !!}" style="max-width: 80%;padding-top: 20px;">
#endforeach

let image_index = 0;
Dropzone.autoDiscover = false;
$(function () {
let feedback_img_upload = new Dropzone('#image_upload', {
paramName: "file",
uploadMultiple: true,
parallelUploads: 5,
maxFilesize: 500,
acceptedFiles: '.jpg, .png, .gif, .pdf, .jpeg',
previewTemplate: document.getElementById('preview').innerHTML,
addRemoveLinks: true,
dictRemoveFile: 'Remove file',
dictFileTooBig: 'Image is larger than 16MB',
timeout: 10000,
url: "/images-save",
init: function () {
this.on("removedfile", function (file) {
let inputObj = $.parseJSON(file['xhr'].response);
$.post({
url: '/images-delete',
data: {id: inputObj.image_name, _token: $('[name="_token"]').val()},
dataType: 'json',
success: function (data) {
if (file.xhr != undefined) {
let imgId = inputObj.file_name;
$('#inquiry_imgfile_' + imgId).remove();
}
return true;
}
});
});
},
});
feedback_img_upload.on("success", function (file, obj) {
if (obj.status == 1) {
image_index++;
$('#inquiry_imgfile_main_div').append('<input class="inquiry_imgfile_upload" id="inquiry_imgfile_' + obj.file_name + '" name="inquiry_imgfile[]" value="" type="hidden"/>');
$("#inquiry_imgfile_" + obj.file_name).val(obj.image_name);
}
});
});
public function store(Request $request)
{
try {
$photos = $request->file('file');
if (!is_array($photos)) {
$photos = [$photos];
}
if (!is_dir($this->photos_path)) {
mkdir($this->photos_path, 0777);
}
$img_names = [];
for ($i = 0; $i < count($photos); $i++) {
try{
$photo = $photos[$i];
$name = date('YmdHisu') . rand(1, 1000000) . $i;
$file_name = $name . rand(1, 1000000);
$resize_name = $file_name . '.' . $photo->getClientOriginalExtension();
$img_names[] = $resize_name;
$photo->move($this->photos_path, $resize_name);
$this->save();
$img = Image::make($photo);
$img->text(' Mysale.lk', 200, 200, function ($font) {
$font->file(public_path('app/OpenSans-Light.ttf'));
$font->size(50);
$font->color('#fdf6e3');
$font->align('center');
$font->valign('top');
});
$img->save($this->photos_path . '/' . $resize_name);
return Response::json([
'image_name' => $resize_name,
"status" => 1,
"file_name" => $file_name
], 200);
exit();
}catch (\Exception $ex){
dd($ex);
}
}
} catch (\Exception $e) {
return Response::json([
"status" => 0
], 401);
exit();
}
}

Related

Kendo Grid inline editing with Kendo Upload return an null result

I had Kendo UI Grid with inline editing and one of my field (propertyLogo) I use kendoUpload to upload an image. With the kendoUpload function fileUploadEditor, I use saveUrl: "./image.php",and convert the image into base64 format to save into database. When I Add/Edit I manage to update all the field successfully except the propertyLogo field it return a NULL result. I do not know which part I'm doing wrong, but I'm not able to save the image into database. Here I'll provide my script.
My DataSource & Grid
/****************/
/** DATASOURCE **/
/****************/
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "./getPropertyMasterData.php",
type: "POST",
data: function() {
return {
method: "getPropertyMasterData",
}
}
},
update: {
url: "./getPropertyMasterData.php",
type: "POST",
data: function () {
console.log("I'm calling update!!");
return {
method: "editPropertyMasterData",
}
},
complete: function (e) {
$('#grid').data('kendoGrid').dataSource.read();
}
},
destroy: {
url: "./getPropertyMasterData.php",
type: "POST",
data: function () {
return {
method: "deletePropertyMasterData",
}
},
complete: function (e) {
$('#grid').data('kendoGrid').dataSource.read();
}
},
},
schema: {
model: {
id: "propertyID",
fields: {
propertyID: { editable: false, nullable: true }
active: { editable: false, nullable: false, defaultValue: 'y'},
propertyName: { editable: true,type: "string",validation: {required: {message: "Required"}} },
propertyLogo: { editable: true, type: "string",validation: {required: {message: "Required"}} },
propertyColor: { defaultValue: "#000", editable: true, validation: { required: {message: "Required"}} },
businessRegistrationNo: { editable: true,type: "string",validation: {required: {message: "Required"}} },
noOfRooms: { defaultValue: 1, editable: true,type: "number",validation: {min: 1, required: {message: "Required"}} }
}
}
},
pageSize: 25
}); // End of Kendo DataSource
/****************/
/** KENDO GRID **/
/****************/
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
sortable: true,
editable: { mode: "inline" },
columns: [
{ field: "active", title:" ", filterable: false,
template: "# if (active=='y'){# <span class='k-icon ehors-status-active-icon'></span> #} else {# <span class='k-icon ehors-status-inactive-icon'></span> # }#"},
{ field: "propertyName", title:"Property Name", width: "80" },
{ field: "businessRegistrationNo", title:"Business Reg. No.", width: "80" },
{ field: "propertyLogo", title:"Logo", width: "80", editor: fileUploadEditor
,template: "<div class='propertyLogo'><a></a>#=propertyLogo#</div>" },
{ field: "propertyColor", title:"Color", width: "80px", editor : getColor, template: function(dataItem) {
return "<div style='background-color: " + dataItem.propertyColor + ";'> </div>";
}},
{ field: "noOfRooms", title:"No of Rooms", width: "80px", format: "", template: "<div class='unit'>#= noOfRooms#</div>" },
//Button Name
{ command: [{ name: "edit", text: {
edit: "Edit",
update: "Update",
cancel: "Cancel"} }
], title: "" }
],
save: onSave, // <-- checking duplicate error.
noRecords: {template: "No Records" }
}).data("kendoGrid"); //end of kendo grid
function fileUploadEditor(container, options) {
$('<input type="file" id="fileUpload" name="fileUpload" /> ')
.appendTo(container)
.kendoUpload({
multiple:false,
async: {
saveUrl: "./image.php",
autoUpload: true,
},
validation: {
allowedExtensions: [".jpg", ".png", ".jpeg"]
},
success: onSuccess, // just a console log to view progress
upload: onUpload, // just a console log to view progress
progress: onProgress // just a console log to view progress
});
}
My image.php
Image will convert into base64 and store into hexString variable. Once getPropertyMasterData.php been called it will fetch hexString value. Currently in here I can see it successful return a value.
<?php
$file = $_FILES['fileUpload'];
$fileName = $_FILES['fileUpload']['name'];
$fileTmpName = $_FILES['fileUpload']['tmp_name']; //directory location
$fileSize = $_FILES['fileUpload']['size'];
$fileError = $_FILES['fileUpload']['error']; //default 0 | 1 got error
$fileExt = explode('.', $fileName); //split file name to get ext name.
$fileActualExt = strtolower(end($fileExt)); //change to lowercase for the extension file
$allowed = array('jpg','jpeg','png');
if (!in_array($fileActualExt, $allowed)) {
return ['error' => 'You cannot upload files of this type!'];
}
if ($fileError !== 0) {
return ['error' => 'Error occur when upload file!'];
}
if ($fileSize > 500000) {
return ['error' => 'Your file size is too big!'];
}
$fileDestination = './uploads/' . $fileName;
move_uploaded_file($fileTmpName, $fileDestination);
$data = file_get_contents($fileTmpName);
return ['hexString' => base64_encode($data)];
?>
My getPropertyMasterData.php
Supposedly $uploadPayload['hexString'] will fetch a variable from image.php but somehow it return NULL result. Other fields works fine.
<?php
$propertyID = "1";
include($_SERVER['DOCUMENT_ROOT'] . '/TM.pdo.php');
$ehorsObj = new TM();
$ehorsObj->TM_CONNECT($propertyID);
$uploadPayload = require "image.php"; // READ FILE FROM image.php | Return NULL result
if (isset($uploadPayload['error'])) {
// echo $uploadPayload['error']);
/* do something in case of error */
}
$method = $_POST['method'];
switch ($method){
case "getPropertyMasterData" :
$method($ehorsObj);
break;
case "editPropertyMasterData" :
$method($ehorsObj, $uploadPayload['hexString']);
break;
default:
break;
}
/** READ **/
function getPropertyMasterData($ehorsObj) {
$getcheckbox = (isset($_POST['c1']) ? $_POST['c1'] : "all"); // by default select *
$sql = "SELECT * FROM tblAdmProperty ";
if ($getcheckbox == "true") {
$sql .= " WHERE active = 'y' ";
}
$sql .= " ORDER BY 2 ASC " ;
$array = array();
$GetResult = $ehorsObj->FetchData($sql, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
while ($row = $GetResult->fetch()){
$array[] = $row;
}
header("Content-type: application/json");
$result = json_encode($array);
echo $result;
}
/** EDIT **/
function editPropertyMasterData($ehorsObj, $NewHexString) {
$propertyID = (isset($_POST['propertyID']) ? $_POST['propertyID'] : '');
$propertyName = (isset($_POST['propertyName']) ? $_POST['propertyName'] : '');
$propertyLogo = (isset($_POST['propertyLogo']) ? $_POST['propertyLogo'] : '');
$propertyColor = (isset($_POST['propertyColor']) ? $_POST['propertyColor'] : '');
$businessRegistrationNo = (isset($_POST['businessRegistrationNo']) ? $_POST['businessRegistrationNo'] : '');
$noOfRooms = (isset($_POST['noOfRooms']) ? $_POST['noOfRooms'] : '');
$active = (isset($_POST['active']) ? $_POST['active'] : '');
$sqlUpdate = " UPDATE tblAdmProperty
SET propertyName = '" . $propertyName . "',
propertyLogo = '" . $NewHexString . "',
propertyColor = '" . $propertyColor . "',
businessRegistrationNo = '" . $businessRegistrationNo . "',
noOfRooms = '" . $noOfRooms . "',
active = '" . $active . "'
WHERE propertyID = '" . $propertyID . "' ";
$ehorsObj->ExecuteData($sqlUpdate, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
}
?>
It works if I use cookies or session but I try to avoid using that. I hope I provide a clear explanation.
Finally, I manage to get it works.
First, I create a hidden textbox <input type="hidden" id='uploadedFile' data-bind="value: propertyLogo" />
Fixed my fileUploadEditor function and add remove.php (optional). onSucces event will fetch the server response in image.php and push into textbox value which I create before.
function onSuccess(e) {
console.log(e.response);
/* push server respoonse to texbox */
$("#uploadedFile").val(e.response);
}
function fileUploadEditor(container, options){
$('<input type="file" id="propertyLogo" name="propertyLogo" /> ')
.appendTo(container)
.kendoUpload({
multiple:false,
async: {
saveUrl: "image.php",
removeUrl: "remove.php",
autoUpload: true,
},
validation: {
allowedExtensions: [".jpg", ".png", ".jpeg"]
},
success: onSuccess
});
$("<span class='k-invalid-msg' data-for='propertyLogo'></span>").appendTo(container);
}
image.php after convert into base64, it need to be in json format
<?php
$fileParam = "propertyLogo";
$uploadRoot = "uploads/";
$files = $_FILES[$fileParam];
if (isset($files['name'])){
$error = $files['error'];
if ($error == UPLOAD_ERR_OK) {
$fileSize = $files['size'];
if ($fileSize < 500000) { //500000 = 500mb
$targetPath = $uploadRoot . basename($files["name"]);
$uploadedFile = $files["tmp_name"];
/* get a full paths */
$fullpath = getcwd();
$newTargetPath = $fullpath . '/' . $targetPath;
move_uploaded_file($uploadedFile, $newTargetPath);
/* convert data into base64 */
$data = file_get_contents($uploadedFile);
$hex_string = base64_encode($data);
header('Content-Type: application/json');
echo json_encode($hex_string);
} else {
echo "Your file size is too big! ";
}
} else {
echo "Error code " . $error;
}
}
// Return an empty string to signify success
echo "";
?>
remove.php
<?php
$fileParam = "propertyLogo";
$uploadRoot = "uploads/";
$targetPath = $uploadRoot . basename($_POST["name"]);
unlink($targetPath);
echo "";
?>
Lastly on my Kendo ui Grid save event i add this line, basically fetch the value from textbox and set into my propertyLogo field
save: function(e){ e.model.set("propertyLogo",$("#uploadedFile").val()); }

Multiple Image Upload using Ajax with Laravel 5.6

First I want Apology for my eng.
Second I don't want to use any plugin.
I Want to upload Multiple image and I can do it without ajax, But I want to upload with Ajax.
I Put my Code here.
<form action="{{route('image-upload.store')}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<input type="file" id="image-upload" name="image_upload[]" enctype="multipart/form-data" multiple>
<button type="submit">save</button>
</form>
Controller :
if ($request->hasFile('image_upload')) {
$images = $request->file('image_upload');
foreach ($images as $image) {
$randonName = rand(1, 200);
$name = $image->getClientOriginalName();
$storename = $randonName . '_' . $name;
$image->move(public_path('images/test'), $storename);
}
}
return redirect()->back();
Above Code simply upload multiple image without Ajax.
Here Ajax :
html :
<input type="file" id="image-upload" name="image_upload[]" enctype="multipart/form-data" multiple>
Ajax :
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$('#image-upload').change(function () {
event.preventDefault();
let image_upload = new FormData();
let TotalImages = $('#image-upload')[0].files.length; //Total Images
let images = $('#image-upload')[0];
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images', images.files[i]);
}
image_upload.append('TotalImages', TotalImages);
$.ajax({
method: 'POST',
url: '/image-upload',
data: image_upload,
contentType: false,
processData: false,
success: function (images) {
console.log(`ok ${images}`)
},
error: function () {
console.log(`Failed`)
}
})
})
Controller :
if ($request->images) {
$images = $request->images;
$total=$request->TotalImages;
$imagesName = $images->getClientOriginalName();
$randonName = rand(1, 200);
$images->move(public_path('/images/test'), $randonName . '.jpg');
return response()->json($randonName);
}
Now This Code Work Fine but only for one image. I know that I Sould put it Loop and I did But didn't get my Response.
So if anyone can tell me how do it?
Here My Efforts :
if ($request->images) {
$total=$request->TotalImages;
$images = $request->images;
for($j=0; $j<$total;$j++){
$imagesName = $images->getClientOriginalName();
$randonName = rand(1, 200);
$images->move(public_path('/images/test'), $randonName . '.jpg');
}
return response()->json($randonName);
}
if ($request->images) {
$images = $request->images;
foreach ($images as $image) {
$imagesName = $images->getClientOriginalName();
$randonName = rand(1, 200);
$image->move(public_path('/images/test'),$randonName . $imagesName . $randonName . '.jpg');
}
}
this gonna work too this will send array of images so as to get it easily in controller
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images[]', images.files[i]);
}
update your code as follows:
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images', images.files[i]);
}
to
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images' + i, images.files[i]);
}
this should help you to submit multiple images.

How to upload image in codeigniter using ajax with server validation

I have a form which data is inserting into data base through ajax. Along with when input fields has error then showing error under neath to the every fields.
But when i select the image and trying to upload the name of image into database, then nothing goes on, neither image uploading to the upload path nor inserting the name of the image into database.
In Case of image upload error i can not even display image upload error.
Controller:-
In my Controller as you can see that i have an array named result which has two keys status and message and default status is false.
In the else part a loop is running which has only form error not any type of image error may be this is reason for not showing any error for image.
No Problem if error is not showing But at least file name should be inserting.
function infoValidation() {
$result = array('status' => false, 'message' => array());
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run('company_registration')) {
$config['upload_path'] = 'assets/uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data['upload_data'] = $this->upload->data('file_name');
$image_name = $data['upload_data'];
//$result['message'] = $this->upload->display_errors();
//$result['status'] = false;
}
else
{
$image_name = '';
}
$data = array(
'email' => $this->input->post('email'),
'first_name' => $this->input->post('firstname'),
'last_name' => $this->input->post('lastname'),
'pincode' => $this->input->post('pincode'),
'state' => $this->input->post('state'),
'landmark' => $this->input->post('landmark'),
'address' => $this->input->post('address'),
'state' => $this->input->post('state'),
'image' => $image_name,
'joined_date' => date('Y-m-d H:i:s')
);
$result['status'] = true;
$this->Perfect_mdl->c_insert($data);
}else {
foreach ($_POST as $key => $value) {
$result['message'][$key] = form_error($key);
}
}
echo json_encode($result);
}
Ajax:
$("#form").submit(function(e){
e.preventDefault();
var me = $(this);
$.ajax({
url : me.attr('action'),
dataType : 'json',
type : 'POST',
data : me.serialize(),
success: function(resp) {
console.log(resp);
if (resp.status == true) {
$('#myModal').modal('show');
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
}else {
$('#msg').html('<div class="alert alert-danger"><h5>Please Check Your Details</h5></div>');
$.each(resp.message, function(key, value) {
var element = $("#"+key);
element.closest('.form-group')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
if(element.parent('.input-group').length) {
element.parent().after(value);
} else {
element.after(value);
}
// element.after(value);
});
}
}
});
});
How can i Upload an image into database, If this is not the right way then please Suggest the right way for doing this
serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
View
<form action="Your controller method name" method="post" id="form_img" enctype="multipart/form-data" accept-charset="utf-8">
<div>
username : <input type="text" name="name">
<span class="error name"></span>
</div>
<div>
password : <input type="text" name="password">
<span class="error password"></span>
</div>
<div>
file : <input type="file" name="image">
<span class="error image"></span>
</div>
<input type="submit" name="submit" value="submit">
</form>
Jquery call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
dataType : 'json',
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
}
});
});
});
</script>
controller
function test_image() {
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run() == TRUE) {
if($_FILES['image']['error'] != 0) {
$result['status'] = false;
$result['message'] = array("image"=>"Select image to upload");
} else {
$config['upload_path'] = 'images';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data['upload_data'] = $this->upload->data('file_name');
$image_name = $data['upload_data'];
}
else
{
$image_name = '';
}
$data = array(
'name' => $this->input->post('name'),
'password' => $this->input->post('password'),
'image' => $image_name,
'joined_date' => date('Y-m-d H:i:s')
);
$result['status'] = true;
$this->Perfect_mdl->c_insert($data);
$result['message'] = "Data inserted successfully.";
}
}else {
$result['status'] = false;
// $result['message'] = validation_errors();
$result['message'] = $this->form_validation->error_array();
}
echo json_encode($result);
}
Try this flow for upload image using ajax
Files cannot be uploaded with serialize() function, as it does not serialize files. Please try this approach:
var data = new FormData(this);
$.ajax({
url : me.attr('action'),
dataType : 'json',
contentType : false,
processData : false,
type : 'POST',
data : data,
success: function(resp) { ... etc.
try this codein view
$('#formElement').submit(function () {
var formData = new
FormData(document.getElementById("formElement"));
formData.append('image-file', $('#image-file')[0].files[0]);
$.ajax({
url: "<?php echo base_url('home/add')?>",
data: formData,
contentType: false,
processData: false,
type: 'POST',
beforeSend: function() {
$('.loder_img').show();
},
success: function ( data ) {
$('.loder_img').hide();
var val = JSON.parse(data);
//you can apply alerts or anything to show validation on
view and in val all mesg of validation yon can see here in console.
console.log(val);
},
error: function (request, status, error) {
$('.loder_img').hide();
alert(request.responseText);
}
});
});
and in your controller
public function addPackage()
{
$this->load->library("form_validation");
//left side form
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('txt_desc', 'Remarks', 'required|trim');
$this->form_validation->set_rules('txt_store', 'Store', 'required|trim');
//upto so on according to your values
if( $this->form_validation->run() == false){
$error = array(
"check_1" => form_error('check_1'),
"txt_desc" => form_error('txt_desc'),
"txt_store" => form_error('txt_store'),
"txt_couple_name" => form_error('txt_couple_name'),
"txt_couple_case" => form_error('txt_couple_case'),
"txt_phone" => form_error('txt_phone'),
"txt_date" => form_error('txt_date'),
"txt_location" => form_error('txt_location'),
"txt_address" => form_error('txt_address'),
"txt_email" => form_error('txt_email'),
);
$msg = array('status' => 'invalid', 'msg'
=>$error,'allerror'=>validation_errors());
echo json_encode($msg);
}else{
//insert it into database all file and values
if($_FILES["image-file"]["size"] != 0){
$path= './uploads/image';
$img = "image/".$this->Upload_model->image_upload($path, "", '', '', '',"image-file");
}
$data = array(
"basket" => $this->filter($this->input->post("check_1",true))........
);
//your insert query
}
}
and in your model to upload image and it will return the uploaded image if it is not upload hen it will return false or you can print the display errors and dont forget to change the path of storing image
model code
public function image_upload($upload_path, $max_width, $max_height, $min_width, $min_height, $filename)
{
$config['upload_path'] = $upload_path;
$config['file_name'] = date('Ymd_his_').rand(10,99).rand(10,99).rand(10,99);
$config['allowed_types'] = "gif|jpg|png|jpeg|JPG|JPEG|PNG|bmp";
$config['overwrite'] = FALSE;
$config['max_size'] = '0';
$config['max_width'] = $max_width;
$config['max_height'] = $max_height;
$config['min_width'] = $min_width;
$config['min_height'] = $min_height;
$config['max_filename'] = '0';
$config['remove_spaces'] = FALSE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($filename))
{
/*$data['upload_data']['file_name'] = '';
$msg = $this->upload->display_errors('');
$this->session->set_flashdata('msg',$msg);
$url = $_SERVER['HTTP_REFERER'];
redirect($url); */
return false;
//return $error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$config['source_image'] = $config['upload_path'].$data['upload_data']['file_name'];
$config['quality'] = '100%';
$this->load->library('image_lib', $config);
return $data['upload_data']['file_name'];
}
unset($config);
$this->image_lib->clear();
}
Jquery serialize() method not able to post file data.
Please used jquery plugin for post file data using ajax. which are given below.
dmuploader.js
dmuploader.min.js
for simple example click here

unable to create thumb nail in php

Am using PHP to create thumbnail from following code but when i run code i get following ERROR
Notice: Undefined variable: phpThumb in C:\Users\logon\Documents\NetBeansProjects\rename multiple file with rename frm single input\for.php on line 42
Fatal error: Call to a member function setSourceFilename() on a non-object in C:\Users\logon\Documents\NetBeansProjects\rename multiple file with rename frm single input\for.php on line 42
since am uploading multiple file how do i create thumb for all formate images
PHP processing code for uploading multiple image and creating thumb
<?php
$newname = uniqid() . '_' . time();
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files'])) {
$errors = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data";
if (empty($errors) == true) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false) {
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
} else { // rename the file if another one exist
$new_dir = "$desired_dir/" . $newname . $file_name;
rename($file_tmp, $new_dir);
}
} else {
print_r($errors);
}
}
if (empty($error)) {
echo "FILE : $file1<br>";
echo "FILE : $file2<br>";
echo "FILE : $file3<br>";
echo "FILE : $file4<br>";
echo "FILE : $file5<br>";
//thumb creation
$files = array("$file1", "$file1", "$file1", "$file1", "$file1");
foreach ($files as $file) { // here's part 1 of your answer
$phpThumb->setSourceFilename($file);
$phpThumb->setParameter('w', 100);
$outputFilename = "thumbs/" . $file;
if ($phpThumb->GenerateThumbnail()) {
if ($phpThumb->RenderToFile($outputFilename)) { // here's part 2 of your answer
// do something on success
} else {
//failed
}
} else {
// failed
}
}
}
}
?>
Edited again to reflect the posters new wishes of how the user experience should be. Now has a drag-drop with preview OR manual selection of 5 files. The drag-drop is submitted by a ajax post, so watch the console for the result. Display and flow needs to be streamlined, but shows a technical working example. The same PHP code handles both results.
<html>
<body>
<pre><?
print_r($_FILES); //SHOW THE ARRAY
foreach ($_FILES as $file) {
if (!$file['error']) {
//PROCESS THE FILE HERE
echo $file['name'];
}
}
?></pre>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var fd = new FormData();
$(document).ready(function() {
//submit dragdropped by ajax
$("#dropsubmit").on("click", function(e) {
$.ajax({
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
//FILES POSTED OK! REDIRECT
console.log(data);
}
});
})
var dropzone = $("#dropzone");
dropzone.on('dragenter', function (e) {
$(this).css('background', 'lightgreen');
});
//dropped files, store as formdata
dropzone.on('dragover', stopPropagate);
dropzone.on('drop', function (e) {
stopPropagate(e)
$(this).css('background', 'white');
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
preview(files[i])
fd.append('file' + (i + 1), files[i]);
if (i >= 5) continue
}
});
function stopPropagate(e) {
e.stopPropagation();
e.preventDefault();
}
if (window.File && window.FileList && window.FileReader) {
$("input[type=file]").on("change", function(e) {
preview(e.target.files[0])
});
} else {
alert("Your browser doesn't support to File API")
}
function preview(item) {
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
src: file.result,
title: file.name,
}).appendTo("#images");
});
fileReader.readAsDataURL(item);
}
});
</script>
<div id="dropzone" style="width:100px;height:100px;border:2px dashed gray;padding:10px">Drag & Drop Files Here</div>
<input type="button" id="dropsubmit" value="Submit dropped files" />
<hr>
<form method="post" enctype="multipart/form-data">
<input id="file1" name="file1" type="file"/><br>
<input id="file2" name="file2" type="file"/><br>
<input id="file3" name="file3" type="file"/><br>
<input id="file4" name="file3" type="file"/><br>
<input id="file5" name="file3" type="file"/><br>
<input name="submit" type="submit" value="Upload files" />
</form><div id="images"></div>
</body>
</html>

Upload a file using AJAX and PHP

I'm trying to make a script to upload files to my server.
What's really bothering me is that the success call is executed though the file is not uploaded.
HTML
<form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
<label>Castellà</label><input name="mapa_es" id="mapa_es" type="file" />
<div id="progressbox_es" style="display:none;">
<div id="progressbar_es">
<div id="statustxt_es">0%
</div>
</div>
</div>
</form>
JS
$(document).ready(function() {
$('#mapa_es').change(function() {
var formData = (this.files[0]);
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
console.log(percentComplete + '%');
//Progress bar
$('#progressbox_es').show();
$('#progressbar_es').width(percentComplete + '%')
$('#progressbar_es').css('background-color', '#6699FF');
$('#statustxt_es').html(percentComplete + '%');
if (percentComplete > 50)
{
$('#statustxt_es').css('color', '#000');
}
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
//Progress bar
$('#progressbox_es').show();
$('#progressbar_es').width(percentComplete + '%');
$('#progressbar_es').css('background-color', '#6699FF');
$('#statustxt_es').html(percentComplete + '%');
if (percentComplete > 50)
{
$('#statustxt_es').css('color', '#000');
}
console.log(percentComplete + '%');
}
}, false);
return xhr;
},
url: 'processupload.php',
type: 'POST',
data: formData,
async: true,
beforeSend: function() {
},
success: function(msg) {
console.log(msg);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
and the PHP code in processupload.php
<?php
if (isset($_FILES["mapa_es"]) && $_FILES["mapa_es"]["error"] == UPLOAD_ERR_OK) {
$UploadDirectory = 'mapes/';
if ($_FILES["mapa_es"]["size"] > 5242880) {
echo "File size is too big!";
}
$File_Name = strtolower($_FILES['mapa_es']['name']);
$File_Ext = substr($File_Name, strrpos($File_Name, '.'));
$Random_Number = rand(0, 9999999999);
$NewFileName = $Random_Number . $File_Ext;
if (move_uploaded_file($_FILES['mapa_es']['tmp_name'], $UploadDirectory . $NewFileName)) {
echo 'Success! File Uploaded.';
} else {
echo 'error uploading File!';
}
} else {
echo 'Something wrong with upload!';
}
?>
I will appreciate any help you could give me. Thanks.
EDIT: I followed gtryonp suggestions and I got into more problems.
When I try to var_dump($_FILES) all I get is an empty string.
I also tried to submit the form using $().submit instead on $().change and it worked, I think it may be because of "enctype="multipart/form-data" on the form tag.
Is there any way to achieve it without having to submit the whole form?
Your processupload.php is ending with a die(message) and will be take as a normal program end, so the success event will be fired and the console.log('FILE UPLOADED') will be your response always, even in error cases. Change all your die(message) with echo message, something like:
if (move_uploaded_file($_FILES['mapa_es']['tmp_name'], $UploadDirectory . $NewFileName)) {
echo 'Success! File Uploaded to '.$UploadDirectory . $NewFileName;
} else {
echo 'error uploading File!';
}
...
and change the success function for something that echoes the possible answers to your screen. Something like:
success: function(msg) {
console.log(msg);
},
HAGD

Categories