I have created multiple image upload function with preview and remove option. But when i select files ,suppose 4 images and then it previews 4 images correctly. Now i remove 2 of them from preview and try to upload in database but it still uploading 4 images instead of 2 image.
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#vpb-data-file").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" height=\"100\" width=\"100\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove</span>" +
"</span>").insertAfter("#ml_image");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
// Old code here
/*$("<img></img>", {
class: "imageThumb",
src: e.target.result,
title: file.name + " | Click to remove"
}).insertAfter("#files").click(function(){
$(this).remove();
});*/
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
<div class="card-body">
<div class="row" id="ml_image" style="margin-top:15px;">
<div class="col-md-3">
<label class="form-label">Upload Image<br>
<span style="font-size:12px;">(For multiple images press ctrl.)</span>
</label>
</div>
<div class="col-md-6">
<span onclick="product_image();" id="hide_span" class="btn btn-icon btn-primary file_upload_icon" style="margin-top:6px;"><i class="fas fa-cloud-upload-alt" style="font-size:31px;"></i><strong style="color:#000000;padding:10px;font-size:15px;">Choose File...</strong></span><input
style="display:none;" type="file" name="p_image[]" id="vpb-data-file" multiple />
</div>
</div>
<div class="row" id="vpb-display-preview"></div>
</div>
$p_image = count($_FILES['p_image']['name']);
print_r($p_image);
Here I am counting how many files I want to upload. I am getting 4 instead of 2.
Your remove function must remove file in e.target.files or in the p_image[] tab.
Related
I'm trying to create a system of photos of a product, where the administrator if he wants to add remove or change the position of the photos he does everything by the form.
Form:
<form role="form" id="editProductForm" enctype="multipart/form-data">
<div id="SubPhotos" class="mt-3" style="overflow: auto; white-space: nowrap;">
<hr>
<div class="form-group mt-0 col-md-3">
<label for="uploadPhoto" class="btn btn-primary" role="button" style="cursor:pointer">Add Photo <i class="fas fa-plus"></i></label>
<input type="file" id="uploadPhoto" onchange="readURL(this);" style="display:none;">
</div>
<div class="d-flex">
<label><span id="badgeMainPicture" class='badge badge-primary ml-2'>Main Picture</span></label>
<label class="ml-auto"><span id="badgeTotalPhotos" class='badge badge-secondary'>Amount of Photos: <?php echo count($productImages) ?> de 10</span></label>
</div>
<div id="droppable" style="display: flex;">
<?php $index = 1;
for ($i = 0; $i < count($productImages); $i++) { ?>
<div id="photo<?php echo $index ?>" class="form-group col-lg-3 draggable">
<img id="preview-img" <?php echo isset($productImages[$i]) ? 'src="' . $site . $productImages[$i]['ImagePath'] . '"' : '' ?> height="300px" width="242px" />
<button id="removerPhoto<?php echo $index ?>" class="btn btn-danger btn-removerPhoto shadow-lg" type="button" onclick="removePhoto(<?php echo $index ?>)"><i class="fas fa-times"></i></button>
</div>
<?php
$index++;
} ?>
</div>
</div>
<hr>
<div class="d-flex">
<button type="submit" id="editProduct" class="ml-auto mr-auto btn btn-primary mt-5">Modify Product</button>
</div>
</form>
Contains remove button, draggable to change positions and add photos, everything works fine CLIENT-SIDE
After submit form:
$("#editProductForm").submit(function(e) {
e.preventDefault();
var index = 1;
$(".draggable").each(function() {
var image = $(this).find("#preview-img").attr("src");
var id = $(this).attr("id").substring(4);
if (image.indexOf("https://") > -1) {
$("#photo" + id).attr("id", "photo" + index);
} else {
$("#picture" + id).attr("name", "picture" + index);
}
index++;
});
var formData = new FormData(this);
var index = 1;
$(".draggable").each(function() {
var image = $(this).find("#preview-img").attr("src");
var id = $(this).attr("id").substring(4);
if (image.indexOf("https://") > -1) {
formData.append('picture' + index, image);
} else {
$("#picture" + id).attr("name", "picture" + index);
}
index++;
});
$.post({
url: '<?php echo $site ?>/admin/painel/modifyproduct.php',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
}
});
});
Now comes the question, my code has bug and I don't know how to solve SERVER-SIDE:
function createImage($id, $productCategory)
{
global $db;
$db->query("DELETE FROM pictures WHERE ProductID='$id'");
if (!file_exists("../../../pictures/produtos/$productCategory/MTA$id/")) {
mkdir("../../../pictures/produtos/$productCategory/MTA$id/", 0777, true);
}
$position = 0;
for ($i = 1; $i <= 10; $i++) {
if (isset($_FILES['picture' . $i])) {
$file = $_FILES['picture' . $i]['tmp_name'];
$nameFile = "picture" . $position;
$patchImage = "/pictures/produtos/$productCategory/MTA$id/$nameFile.png";
move_uploaded_file($file, "../../.." . $patchImage);
saveImageInDataBase($id, $patchImage, $position);
$position++;
} else if (isset($_POST['picture' . $i])) {
$file = $_POST['picture' . $i];
$nameFile = "picture" . $position;
$oldName = "../../../" . substr($file, strpos($file, 'pictures/'));
rename($oldName, "../../../pictures/produtos/$productCategory/MTA$id/$nameFile.png");
saveImageInDataBase($id, "/pictures/produtos/$productCategory/MTA$id/$nameFile.png", $position);
$position++;
}
}
}
Bug: There is a bug that when there is already a photo in the folder with the same name (with the position) and another photo being placed with that same position (move_uploaded_file) the old photo will be replaced.
Would there be an easier way to make this photo system work well?
Before doing the move_uploaded_file() you have to check whether the file exists. If so, you'll need to create a new filename. You'll have to do those steps until you find a non-existent file.
while ( TRUE ) { // Loop until we find a non-existent destination filename
$nameFile = "picture" . $position;
$patchImage = "/pictures/produtos/$productCategory/MTA$id/$nameFile.png";
if ( ! file_exists( $patchImage ) ) { // We're good
move_uploaded_file($file, "../../.." . $patchImage);
saveImageInDataBase($id, $patchImage, $position);
break; // Get out of the loop
}
$position++; // Try next position
}
I would like to upload multiple images using single input tag(with image preview) and without use multiple attribute in input tag, I have used following script but i could not help it always take last input image in array not whole images.
HTML
<form id="profile-photos-form" class="profile_image_gallery" name="profile_image_gallery" action="{{ URL::to('create_profile')}}" method="post" enctype="multipart/form-data">
<div class="mdb-lightbox no-margin " id="result">
<input type="file" name="photos[]" id="files">
<div class="width-33 gallary-image-profile-pic">
<!-- Following is only for set profile image from upload images -->
<a class="spotlight" href="">
<img class="photo_class" name="profile_image" src="" class="img-fluid">
<input type="hidden" name="profile_pic" id="profile_pic" value="">
</a>
<div class="icons-images">
<i class="fa fa-plus icon_delete_add" aria-hidden="true" style="color: white;"></i>
<i class="fa fa-trash icon_delete_add" aria-hidden="true" style="color: white;"></i>
</div>
</div>
<!-- Uploaded image preview will show here -->
<div id="thumb-output"></div>
</div>
</form>
JS
window.onload = function(){
if(window.File && window.FileList && window.FileReader){
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function(event){
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for(var i = 0; i< files.length; i++) {
var file = files[i];
//Only pics
if(!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
console.log(picFile)
var div = document.createElement("div");
var div1 = document.createElement("div");
div.classList.add("width-16");
div.classList.add("gallary-image");
div.innerHTML = "<img name='image_gallery[]' class='photo_class' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div,null);
});
picReader.readAsDataURL(file);
}
});
}else{
console.log("Your browser does not support File API");
}
}
PHP Laravel Controller code
<?php
namespace App\Http\Controllers\escortProfile;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Cartalyst\Sentinel\Checkpoints\NotActivatedException;
use Cartalyst\Sentinel\Checkpoints\ThrottlingException;
use Cartalyst\Sentinel\Laravel\Facades\Activation;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redire;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
use App\Mail\UserRegistration;
use App\UserDetails;
use App\User;
use App\Roles;
use App\Locations;
use DB;
use Response;
use File;
use App\Http\Middleware\Admin;
class profileController extends Controller{
public function createProfile(Request $request){
if ($image = $request->file('photos')) {
foreach ($image as $files) {
$destinationPath = 'public/image/'; // upload path
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
$insert[]['image'] = $profileImage;
}
}
}
}
This code only return last input image in array not return all the images, I want all the images and also move all the uploaded images in folder and database.
NOTE: currently i have not written DB store code.
Hello I Am Working On A Startup and I Have A Huge Problem In My Project.
In Searching Page User Can Search By Different Item And Ads Showed.
I Wanna Per Each Ad In The Picture Area Shows Picture By Slider.
Let Me Show By Pic .
This Is Searching Page
Searchin_Page
I Wanna Use Slider For Each Ad That Shows But Its Dose not Work True . . .
This Is My Jquery Code
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function currentDiv(n) {
showDivs(slideIndex = n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
if (n > x.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = x.length
}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" w3-white", "");
}
x[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " w3-white";
}
And This Is Html Side . . .
<div class="Image_Area_Panel">
<div class="w3-content w3-display-container" style="max-width:800px">
<img class="mySlides" src="http://localhost/Ajency/Public/456d6ef5aae4e33926a4c592aa5210a5--sexy-men-hot-men.jpg">
<img class="mySlides" src="http://localhost/Ajency/Public/620b1b643b4d40bef759a386764fc630.jpg">
<img class="mySlides" src="http://localhost/Ajency/Public/Brant-daugherty-cuff.jpg">
<div class="w3-center w3-container w3-section w3-large w3-text-white w3-display-bottommiddle Aroos" style="width:100%">
<div class="AreaBox">
<div class="w3-left w3-hover-text-khaki" onclick="plusDivs(-1)">❮</div>
<div class="w3-right w3-hover-text-khaki" onclick="plusDivs(1)">❯</div>
</div>
<span class="w3-badge demo w3-border w3-transparent w3-hover-white" onclick="currentDiv(1)"></span>
<span class="w3-badge demo w3-border w3-transparent w3-hover-white" onclick="currentDiv(2)"></span>
<span class="w3-badge demo w3-border w3-transparent w3-hover-white" onclick="currentDiv(3)"></span>
</div>
</div>
Sorry For My English Ability
I installed BT Property component for my Joomla site and when I select multiple of images (more than 3 or 4) which I want to upload for my article, it nothing happens. The images won't upload. I try to change the code but I don't know what the problem is.
This is the code I want to change.
<?php
defined('_JEXEC') or die('Restricted access');
$document = JFactory::getDocument();
$path = $this->params->get('images_path', 'images/bt_property');
?>
<ul class="adminformlist" id="uploading">
<li><input type="file" name="attachment" id="attachment" multiple /><img id="spinner"
style="display: none; margin-left: 10px;"
src="<?php echo JURI::root(); ?>components/com_bt_property/assets/img/spinner.gif">
<div style="clear: both"></div>
<div id="btss-message"></div></li>
</ul>
<script type="text/javascript">
(function($){
var files = [];
$("#attachment").change(function(event) {
$.each(event.target.files, function(index, file) {
var reader = new FileReader();
reader.onload = function(event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
files.push(object);
if(files.length==1){
uploadFile(index);
$('#spinner').show();
$("#btss-message").show();
}
};
reader.readAsDataURL(file);
});
});
function uploadFile(index){
$.ajax({url: "index.php?option=com_bt_property&task=properties.upload",
type: 'POST',
data: {filename: files[index].filename, filedata: files[index].data},
success: function(response, status, xhr){
uploadHandler(response, status, xhr);
if(index == files.length-1){
$('#spinner').hide();
files = [];
$("#attachment").val('');
$("#btss-message").delay(1000).slideUp(function(){
$("#btss-message").html('');
});
}else{
index++;
uploadFile(index);
}
}
});
}
function uploadHandler(response, status, xhr) {
var data = jQuery.parseJSON(response);
if(data == null){
showMessage("<br /><span style=\"color: red;\">Loading Failed</span>");
}else{
var file = data.files;
if (!data.success) {
showMessage("<br /><span style=\"color: red;\"> " + data.message +"</span>");
}
else {
var html = '<li>';
html += '<input class="input-default" title="Make default" name="default_image" type="radio" value="'+file.filename+'" />';
html += '<img class="img-thumb" src="<?php echo JURI::root() . $path . '/tmp/' . ($this->params->get('thumbimgprocess', 1) == -1 ? 'original' : 'thumb') . '-'; ?>'+file.filename+'" />';
html += '<input type="hidden" name="image_id[]" value="0" />';
html += '<input type="hidden" name="image_filename[]" value="'+file.filename+'" /><br/>';
html +='Edit';
html +='<a href="javascript:void(0)" class="remove" onclick="removeImage(this)" >Remove</a>';
html += '</li>';
jQuery('#sortable').append(html);
jQuery('#sortable li:last-child ').find('a.edit').data('title', file.title);
reNewItem();
showMessage('<br />' + file.title + " uploaded successfully!");
}
}
}
function showMessage(msg){
$("#btss-message").append(msg);
}
})(jQuery);
</script>
Is there a way to fix the code? I would be very thankful for any answer.
Your file object is coming up as undefined, and thus you're not able to use file.filename.
Your problem is most likely with this line var file = data.files; - are you sure about data.files?
I created a while loop that produces five images. I then designed the images to be dragged onto a droppable section of the webpage. I then want the webpage to output the location of where I placed the image. My only problem is that I want the code to also echo out the src from where I got the image from. For some reason, whenever I click on any of the images and drag them, the page only echos out the src of the first image the while loop looped through.
<script type="text/javascript">
$(".droppable").droppable();
</script>
<?php
$num_dresses = dress_count ();
$i = 0;
while ($i < 5)
{
$rand_id = rand(1, $num_dresses);
$new_file_name = html_entity_decode($dress_feed_data['file_name']);
if (file_exists('fashion_images/' . $new_file_name))
{
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function()
{
$(".ui-widget-content").draggable(
{
stop: function(event,ui)
{
var Stoppos = $(this).position();
var className = $("img").attr("src");
$(".location").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top +
className);
}});});});
</script>
<div class="ui-widget-content">
<img src="fashion_images/<?php echo $new_file_name;?> " width="70" height="70"/>
</div>
<?php
}
$i++;
}
?>
<div class="droppable"></div>
<div class="location"></div>
Jason,
Try :
$(".ui-widget-content img").draggable({
stop: function(event, ui) {
var Stoppos = $(this).position();
var className = $(this).attr("src");
$(".location").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top + className);
}
});