How to set max uploaded images - php

I upload images through ajax method in my yii2 app. I can choose multiple files to upload but I need to upload max 5 files. How can I do that?
My view file:
<div class="row">
<div class="col-lg-6">
<p class="add_photo"><img class="describe_images" src="photo.png"></img>Добавить фото(до 5 штук)</p>
<form enctype="multipart/form-data"
"method"="post" "id"="my-form">
<input name="media[]" type="file" multiple id ="gallery-photo-add"/>
<input class="button" type="submit" alt="Upload" value="Upload" />
</form>
</div>
<div class="col-lg-6 pixels-line">
<div class="preview"></div>
</div>
</div>
ajax method which upload a files
<script>
$('#my-form').submit( function(e) {
e.preventDefault();
var data = new FormData(this); // <-- 'this' is your form element
$.ajax({
url: 'site/index',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
});
</script>

Related

Send Image file with Google reCaptcha v2 token to PHP via jQuery + Ajax

I want to POST and upload image via AJAX with Google reCaptcha v2 validation. but I am facing an issue that I am not not able to send image with caption text with google recaptcha token in Ajax. I coded two function as I know but both was not working. The function I made is the code snippet.
Please help me how I send Image with text in Ajax with reCaptcha token in PHP / jQuery/ AJAX.
$(document).ready(function() {
$("form#addbanner").unbind("submit").bind("submit", function(e) {
//debugger;
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('MY_RECAPTCHA_CODE', {
action: 'add_web_banner'
}).then(function(token) {
/*let formData = {
imagehere : $('input[name="imagehere"]').val(),
bannertitle : $('input[name="bannertitle"]').val(),
action : 'add_web_banner',
type: 'add_web_banner'
};*/ //not working
/*let formData = {
var formData = new FormData($("form#addWeb-Banner")[0]);
formData.append('token': token);
};*/ //not working
//*POST Image sent in (binary way), I dont want to use JSON in types*//
$.ajax({
type: 'POST',
data: formData,
cache: false,
success: function(response) {
hide_loader();
if (response.status == "success") {
$("form#addWeb-Banner")[0].reset();
alert("Great");
} else {
alert("Ops!");
}
},
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="bs-example form-horizontal AddWebBanner" id="addbanner" enctype="multipart/form-data" method="POST">
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Upload Image</label>
<div class="col-lg-8">
<input type="file" class="form-control" title="Upload Photo" id="BannerImage" name="imagehere" accept="image/png,image/jpg,image/jpeg" />
</div>
</div>
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Caption of Banner</label>
<div class="col-lg-8">
<input type="text" class="form-control" title="Caption of Banner" name="bannertitle" />
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-lg-12">
<button type="submit" name="submit" class="btn btn-sm btn-default pull-right" id="addBannerBtn">POST</button>
</div>
</div>
</form>
Change your HTML and formData to the following
Give an id selector your caption banner.
<input type="text" class="form-control" id="caption_banner" title="Caption of Banner" name="bannertitle" />
Store using the formData like this and then sent formData via ajax
var formData = new FormData();
//Append Image
formData.append('file', $('#BannerImage')[0].files[0]);
//Append banner caption
formData.append('caption', $('#caption_banner').val());
You can also use jQuery .serialize method to send data to your backend via ajax
var formData = $('form#addbanner').serialize()
thank for #AlwaysHelping but there was one mistake but I has been fix that..below are the correct answer for future user troubles..
I not mentioned processData: false, contentType: false, in ajax.. so the final code will be..
var formData = new FormData();
formData.append('file', $('#BannerImage')[0].files[0]);
formData.append('caption', $('#caption_banner').val());
$.ajax({
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (response) { ... }
peace :)

image upload using ajax in Laravel

I have an user information form in my Laravel site and trying to upload image using Ajax.
Blade
<form id="edit_form" enctype="multipart/form-data">
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
<div class="form-group">
<label>Image</label>
<input id="edit_form_image" type="file" class="form-control" name="user_image">
</div><!-- end form-group -->
<div class="form-group">
<label>Name</label>
<input id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
</div><!-- end form-group -->
<button type="button" id="edit_form_submit" class="btn btn-orange">Save Changes</button>
Ajax
$('#edit_form_submit').click(function(event) {
var fd = new FormData();
var edit_form_image = $('#edit_form_image')[0].files;
var edit_form_name = $('#edit_form_name').val();
var token = $('input[name=_token]').val();
fd.append( 'image', edit_form_image );
fd.append( 'name', edit_form_name );
fd.append( '_token', token );
$.ajax({
url:"{{ url('/profile-update') }}",
data: fd,
async:false,
type: 'POST',
processData: false,
contentType: false,
success:function(msg)
{
console.log(msg);
}
});
});
But in my controller I can't get the image file.
controller
if (request()->hasFile('image'))
{
return "file present";
}
else{
return "file not present";
}
Though I upload an image controller always response that `file no present'.
Where is the error? Anybody Help please ?
why dont you name your input tags as you need to send in post method in :
<input name="image" id="edit_form_image" type="file" class="form-control">
<input name="name" id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
And,
$("#edit_form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url:"{{ url('/profile-update') }}",
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success:function(msg)
{
console.log(msg);
}
});
});
This might works.

Display Two Images on One Click. PHP, AJAX

As I Have 2 Div Boxes. One is Input and the other one is Output Div Box as Shown in the Image Below.:
Now What I am doing is I am uploading the Image using the Help of PHP. And uploading same image on two folders named Input and Output.
What I want is When I Click Submit Button the image from input folder should be shown on Input Box and the Output Folder Image to be shown In Output Folder.
I am able to show the Input folder Image but not able to show the Output folder Image in output Div.
Here is my HTML Code :
<div class="container">
<div class="row">
<div class="col-md-6">
<h2 class="inputImage-text text-center">Input Image</h2>
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<div id="targetLayer">No Image</div>
<div id="uploadFormLayer">
<input name="fileToUpload" type="file" class="inputFile" /><br />
<input type="submit" value="Submit" class="btnSubmit btn btn-primary" />
</div>
</form>
</div>
<div class="col-md-6">
<h2 class="outputImage-text text-center">Output Image</h2>
<div class="outputDiv">
</div>
</div>
</div>
</div>
Here is my php Script:
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$sourcePath = $_FILES['fileToUpload']['tmp_name'];
$targetPath = "input/".$_FILES['fileToUpload']['name'];
$outputImage = "output/".$_FILES['fileToUpload']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
copy($targetPath, $outputImage)
?>
<img class="image-preview" src="<?php echo $targetPath; ?>" class="upload-preview" />
<?php
}
}
}
?>
and Here is the AJAX Code :
<script type="text/javascript">
$(document).ready(function(e) {
$("#uploadForm").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#targetLayer").html(data);
},
error: function() {}
});
}));
});
</script>
Use dataType option to accept the response in JSON format.
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
dataType: "json",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data.input_file);
$(".outputDiv").html(data.output_file);
},
error: function()
{
}
});
}));
});
</script>
Return both input and output files in an array format as follows
<?php
$uploadedFiles = [];
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$sourcePath = $_FILES['fileToUpload']['tmp_name'];
$targetPath = "input/".$_FILES['fileToUpload']['name'];
$outputImage = "output/".$_FILES['fileToUpload']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
copy($targetPath, $outputImage);
$uploadedFiles['input_file'] = '<img class="image-preview" src="'.$targetPath.'" class="upload-preview" />';
$uploadedFiles['output_file'] = '<img class="image-preview" src="'.$outputImage.'" class="upload-preview" />';
}
}
}
echo json_encode($uploadedFiles);
?>
Refer to this documentation regarding dataType
Add this with in your script
$(".outputDiv").html(data);
I have changed your php, html and jquery. You need to add jsonarray instead of html because it would be easy to put multiple data in json array and can get it easily in jquery .
In html i have added img tag to display image in output.
In php script, I have removed html and added json array for both the images.
In jquery script, I have replaced all img tag with src.
<div class="container">
<div class="row">
<div class="col-md-6">
<h2 class="inputImage-text text-center">Input Image</h2>
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<div id="targetLayer">No Image <img src="" id="intput-file-view"/></div>
<div id="uploadFormLayer">
<input name="fileToUpload" type="file" class="inputFile" /><br/>
<input type="submit" value="Submit" class="btnSubmit btn btn-primary" />
</div>
</form>
</div>
<div class="col-md-6">
<h2 class="outputImage-text text-center">Output Image</h2>
<div class="outputDiv">
<img src="" id="output-file-view"/>
</div>
</div>
</div>
</div>
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$sourcePath = $_FILES['fileToUpload']['tmp_name'];
$targetPath = "input/".$_FILES['fileToUpload']['name'];
$outputImage = "output/".$_FILES['fileToUpload']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
copy($targetPath, $outputImage);
echo json_encode(array("inputImage"=>$targetPath,"outputPath"=>$outputImage));
exit;
}
echo json_encode(array("inputImage"=>"","outputPath"=>""));
exit;
}
}
?>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
var response=JSON.parse(data);
if(response.inputImage != "" && response.outputPath != ""){
$("#intput-file-view").attr("src",response.inputImage);
$("#output-file-view").attr("src",response.outputPath);
}
},
error: function()
{
}
});
}));
});
</script>

How to upload image using ajax and codeigniter without resetting the form?

i just wanted to upload an image using ajax and codeigniter. Getting error which is saying "You did not select a file to upload." even i did select that image.
I recently tried many examples from many sources but did not get my answer. following i show you my code this is giving me the result as "You did not select a file to upload." when i already selected the file.
This is my view:
<div class="col-lg-6">
<div class="dropify-wrapper mb-4 form-group col-lg-6">
<div class="dropify-loader"></div>
<div class="dropify-errors-container">
<ul></ul>
</div>
<input class="dropify" name="userfile" id="input-file-now" type="file">
<button class="dropify-clear" type="button">Remove</button>
<div class="dropify-preview">
<span class="dropify-render"></span>
<div class="dropify-infos">
<div class="dropify-infos-inner">
<p class="dropify-filename"><span class="file-icon"></span>
<span class="dropify-filename-inner"></span></p>
<p class="dropify-infos-message">Drag and drop or click to replace</p>
</div>
</div>
</div>
</div>
</div>
This is ajax code:
$('#submit_btn').click(function (e) {
e.preventDefault();
var data = $('#formname').serialize();
$.ajax({
type: 'ajax',
method: 'post',
url: '<?php echo base_url() ?>ControllerName/functionName',
data: data,
enctype: 'multipart/form-data',
async: false,
dataType: 'json',
success: function (response) {
alert(response);
},
error: function () {
}
});
});
This is controller code:
public function functionName()
{
$config=[
'upload_path'=>'./Assets/imgs/users/',
'allowed_types'=>'jpg|png|gif'
];
$this->load->library('upload',$config);
if($this->upload->do_upload(')){
$data=$this->upload->data();
$image_path= base_url("Assets/imgs/users/".$data['raw_name'].$data['file_ext']);
$result= $image_path;
}else{
$result=$this->upload->display_errors('','');
}
}
Please add tag in your html and also use formdata in jquery code like below.
HTML Code:
<form id="form" method="post" enctype="multipart/form-data">
</form>
Jquery Code:
data: new FormData(formid),

I dont get temp name of image upload using php,ajax

I want to get the temp name of image upload using php and ajax.I got the file name of upolad image. But dont get the temp name of image upload.My code is given below
main.php
<form action=" " method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">File Upload</label>
<input type="file" name="file" id="file" size="150">
<p class="help-block">Only Excel/CSV File Import.</p>
</div>
<button type="button" class="btn btn-default"
name="Import" value="Import" onclick="file_up()">
Upload</button>
</form>
<div id="upload_show"></div>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function file_up() {
var file = $('#file').val();
$.ajax({
type: "POST",
url: 'first_ajax.php',
data: 'file=' + file,
success: function (msg){
$("#upload_show").html(msg);
}
});
}
</script>
first_ajax.php
<?php
echo $file1 = $_POST['file']; // for get file name
echo $file1 = $_POST['file']['tmp_name']; //for get temp name
?>
Instead of,
var file = $('#file').val();
try,
var file = $("#file").prop("files")[0];
Use FormData to get $_FILES and $_POST array in AJAX file...
function file_up() {
var formData = new FormData($('#form')[0]);
$.ajax({
url: 'first_ajax.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
$("#upload_show").html(msg);
},
cache: false,
contentType: false,
processData: false
});
}

Categories