Add and delete thumbnail using ajax - php

I need to create and delete thumbnail image in my yii2 app. I must to have max 5 images and when I was choose files I may to see thumbnails of that images.
I added images in my view with that:
?= $form->field($images, 'imagesFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>
and I can get images in my controller:
$images->imagesFiles = UploadedFile::getInstances($images,'imagesFiles');
How can I see thumbnails? I need to create ajax request? If yes, how I can delete different images? Or add them to my view maybe with some id's.

If you want to see images after choosing them from disk, before submit form, you can preview selected files in view using javascript, eg:
$('#gallery-photo-add').on('change', function() {
var input = $(this)[0];
var images = $('#some-div');
for (var i=0; i<input.files.length; i++) {
if (input.files && input.files[i]) {
var reader = new FileReader();
reader.onloadend = function (e) {
images.append('<img src="'+e.target.result+'" />');
};
reader.readAsDataURL(input.files[i]);
}
}
});

Related

During Upload image select images from different folder and preview all images before uploading and upload all images

I am doing multiple image upload using php-Codeigniter. While selecting multiple images I want to select images from multiple folders and preview them before submitting the form and submit all previewed images.
I have used jquery for previewing selected images. But when I select another image old preview image is gone and I am not able to select multiple images from different folders and can not upload all preview images. Also, after uploading, only last selected images gets upload.
jquery:
$(function () {
$("#fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#dvPreview");
dvPreview.html("");
$($(this)[0].files).each(function () {
var file = $(this);
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "height:100px;width: 100px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
view:
I expect to select multiple images from different folders and preview them and user can delete images if user do not want to upload them and then upload all previewed images.

Laravel 4 Can't route ouput from jQuery to Controller

This is a Laravel 4 image manipulation project.
I am going round in circles trying to solve this conundrum, which I am sure has an elementary solution.
The user chooses some images, previews them and then clicks to upload.
The problem is that handleForm's output (the FormData object) does not get routed to the ImageController for the rest of the image handling. On clicking nothing happens. Debugging shows that the FormData object (data in xhr.send(data)) contains the images that the user specified.
The relevant bits: 1 The user clicks to upload.
<input type="button" value="Upload" id="go"/>
In the jQuery the .click event starts handleForm function:
$("#go").on("click", handleForm);
In handleForm the storedFiles array contains the users chosen images after previewing them.
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText);
}
}
xhr.send(data);
}
In Routes
Route::post('upload', array(
'as' => 'upload',
'uses' => 'ImageController#upload'
));
In ImageController:
<?php
class ImageController extends BaseController {
public function upload(){
$files = Input::all('files');
$gallery = str_random(12);
foreach ($files as $file) {
$validation = Image::validateImage(array('file'=> $file));
...................
This is the first time I have tried to incorporate jQuery in Laravel and I need some help!
The answer in this case was to change the jQuery to make files into array files[] like:
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]);
}
I couldn't find this solution anywhere despite hours of searching, it was just a trial and error approach.

Changing img src with the fileupload value using jquery/php/html

I'm working on a facebook tab that accepts some text and also a picture using an html fileUpload component, the idea is that when the user selects a picture in the fileUpload component, the image they select appears on the page as a way of previewing the picture before uploading it to the server. I tried fectching the image url using val(), but for security reasons, browsers do not give the complete url of a local file. Is there a way to do this using either php or jquery?
Thanks
I believe this is what you're looking for:
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
preview.appendChild(img);
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
}
}
You might also be interested in reading other examples, like this one.
Edit: This method relies on the FileReader API, so it won't work on IE9 as you've pointed out, but I don't think it is possible otherwise.
At the end of the day, do you need IE9 compatibility ? You might find it acceptable to add a functionality that works for all but a few percent of your user base.

How to show upload image preview using jquery before form submit in a div

I am dealing with a form that contains various form elements with an option to upload multiple images(upto 6 max). Now i am having a div preview on clicking that div i fetch all form fields using jquery (form still not submitted at this time as its a multi form step1, 2 and 3). Now the problem is that i am fetching all form data with this code -
var allFormData = $("#myform").serializeArray();
Using this another code i am able to show rest of the data in div, but image is not coming.
$.each(adtitletoshow, function(i, field){
if( field.name == 'desc'){
$(".add_desc").text(field.value);
}
});
This is the filed created by JS to upload image.
<script type="text/javascript">
var total_images = 1 ;
function add_file_field () {
total_images++ ;
if ( total_images > 6 ) return ;
var str_to_embed = '<input name="fileImage[]" size="40" style="width: 500px;" type="file" onChange="add_file_field()"><br>' ;
$("#image_stack").append ( str_to_embed ) ;
}
</script>
All things going on single page so i need a solution that how can i load images under my preview div. Let me know if thr is some point of ambiguity still persists.
You need to loop through the files array from the multiple input and use the FileReader API on each.
I've set up the HTML like this:
​<input type="file" multiple="true" id="files" />
<input type="submit" id="go"/>
<div id="images"></div>​​​​​​​​​​​​​​​​​​​​​​
Then the javascript as follows:
// set up variables
var reader = new FileReader(),
i=0,
numFiles = 0,
imageFiles;
// use the FileReader to read image i
function readFile() {
reader.readAsDataURL(imageFiles[i])
}
// define function to be run when the File
// reader has finished reading the file
reader.onloadend = function(e) {
// make an image and append it to the div
var image = $('<img>').attr('src', e.target.result);
$(image).appendTo('#images');
// if there are more files run the file reader again
if (i < numFiles) {
i++;
readFile();
}
};
$('#go').click(function() {
imageFiles = document.getElementById('files').files
// get the number of files
numFiles = imageFiles.length;
readFile();
});
I've set up a JSFiddle to demo http://jsfiddle.net/3LB72/
You'll probably want to do more checks on whether the browser the user is using has FileReader and if the files they have chosen are image files.
JSFiddle demo
This is much better, without clicking any button :D
HTML:
<input type="file" multiple="true" id="files" />
<input type="submit" id="go"/>
<div id="images"></div>
JavaScript:
// set up variables
var reader = new FileReader(),
i=0,
numFiles = 0,
imageFiles;
// use the FileReader to read image i
function readFile() {
reader.readAsDataURL(imageFiles[i])
}
// define function to be run when the File
// reader has finished reading the file
reader.onloadend = function(e) {
// make an image and append it to the div
$("#images").css({'background-image':'url('+e.target.result+')'});
// if there are more files run the file reader again
if (i < numFiles) {
i++;
readFile();
}
};
$('#files').live('change', function(){
imageFiles = document.getElementById('files').files
// get the number of files
numFiles = imageFiles.length;
readFile();
});

Jquery upload function doesn't work for multiple images on 1 page

How it works:
I'm trying to create an instant upload function with Jquery/Ajax. When a user double-clicks an image, a Fancybox shows up with the upload field. After choosing an image, the image is uploaded and the source of the clicked image is changed immediately.
The problem:
When having multiple images on one page, sometimes another image gets replaced by the new image (randomly).
The code:
function uploader(thumb) {
new AjaxUpload('imageUpload', {
action: 'uploader.php',
name: 'file',
onComplete: function(file, response) {
thumb.attr('src', response);
$.fancybox.close();
}
});
}
$("img").dblclick(function(){
var img = $(this);
$.fancybox({
href: '#imageUpload',
overlayShow: true
});
uploader(img);
return false;
});
What I've tried:
When I alert the ID of the image that should be replaced, it always alerts the correct ID of the image. And still it replaces another image instead.
Regards,
Bo
The way you're getting a reference to the clicked image is not good. You should extract the clicked element from the event object passed to the handler.
$('img').dblclick(function(event) {
var img = $(event.target);
...
});

Categories