Display Image's on same page from different folder using jquery - php

This code I get by search..
<html>
<head>
<title>Get url for address bar</title>
<script>
function display(folder,img_name)
{
var src = "http://localhost/UPLOADER/images/"+folder+"/"+img_name;
show_image("http://localhost/UPLOADER/images/"+folder+"/"+img_name, 276,110, "Img");
}
function show_image(src, width, height, alt)
{
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
</script>
</head>
<body>
<input type="text" name="image" value="" style="margin-top: 4px;" placeholder="Image_name" />
<button onclick="display('a','access')">DISPLAY IMAGE</button>
</body>
</html>
This code I take from site for jquery it worls well but I think I done some mistake in my code its not easy to grab the error as it display. undefined image and function display.
I want to add this for dynamic selection of image
<?php
$img_name=$_POST['image'];
$folder = substr($img_name, 0, 1);
?>
<button onclick="display('$folder','$img_name')">DISPLAY IMAGE</button>
for extension I use .htaccess Options +MultiViews
thanks

ok there are many many solutions to this problem, changing it to an ajax call to the php page to get the image/images would be one, a very simple solution would be this...
<?php
$image = (isset($_REQUEST['image'])) ? $_REQUEST['image'] : false;
$folder = ($image) ? substr($image, 0, 1) : false;
?>
<html>
<head>
<title>Get url for address bar</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
var image = '<?php echo ($image) ? $image : "false"; ?>';
var folder = '<?php echo ($folder) ? $folder : "false"; ?>';
var extension = '.jpg';
function DISPLAY(folder,img_name, imgExt) {
var finalExt = (typeof imgExt != 'undefined') ? imgExt : extension;
if(img_name != 'false' && folder != 'false') {
show_image("http://localhost/UPLOADER/images/"+folder+"/"+img_name+finalExt, 276,110, "Img");
} else {
console.log("looks like something was undefined, here's the values:");
console.log(folder);
console.log(img_name);
}
}
function show_image(src, width, height, alt)
{
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
//if using jquery
$(document).ready(function() {
//you could also add logic here to see if values are not 'false' and run function
DISPLAY(folder, image);
});
</script>
</head>
<body>
<form action="" method="POST">
<input type="text" name="image" value="" style="margin-top: 4px;" placeholder="Image_name" />
<button>DISPLAY IMAGE</button>
</form>
</body>
</html>

Related

How to upload multiple images to a folder using ajax php and jquery

I am trying to upload multiple images to a folder at a time by using AJAX, JQuery, and PHP. The code is running for single file upload but not running for multiple image upload.
If I am uploading a single image without loop then its working fine but in case of loop it's not working.
I am using the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
for (var i = 0; i < $('#file').get(0).files.length; ++i) {
names.push($('#file').get(0).files[i].name);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
//PHP Code
<?php
/* Getting file name */
echo "<script>alert('yes');</script>";
//without loop working fine
$count = count($_FILES['file']['name']);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file']['name'][$i];
/* Location */
$location = "upload/".$filename;
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
var file_data = $('input[type="file"]')[0].files;
// for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
have made changes in below code
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
And there are also changes in PHP code
<?php
/* Getting file name */
//without loop working fine
$count = count($_FILES);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file_'.$i];
/* Location */
echo $location = "upload/".$filename['name'];
/* Upload file */
if(move_uploaded_file($filename['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
count of files and file name are comming in a different way so I have made the changes as required instead of if gives file array like $_FILE['file_0'],$_FILE['file_1'] and so on, I have also change the permission of upload directory please check if your directory have read and write permission (777) or not, this code works for me you can try I hope it will work for you also :-)
In the loop you will need to add index of particular file
move_uploaded_file($_FILES['file']['tmp_name'][$i],$location); // $i is index

Display picture after browse, but before upload using laravel [duplicate]

I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.
How can I do this?
imgInp.onchange = evt => {
const [file] = imgInp.files
if (file) {
blah.src = URL.createObjectURL(file)
}
}
<form runat="server">
<input accept="image/*" type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image.
Here's an example:
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
You can also use FileReader.readAsDataURL() to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
</script>
One-liner solution:
The following code uses object URLs, which is much more efficient than data URL for viewing large images (A data URL is a huge string containing all of the file data, whereas an object URL, is just a short string referencing the file data in-memory):
<img id="blah" alt="your image" width="100" height="100" />
<input type="file"
onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">
Generated URL will be like:
blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345
Try This
To PREVIEW the image before uploading it to the SERVER from the Browser without using Ajax or any complicated functions.
It needs an "onChange" event to load the image.
function preview() {
frame.src=URL.createObjectURL(event.target.files[0]);
}
<form>
<input type="file" onchange="preview()">
<img id="frame" src="" width="100px" height="100px"/>
</form>
To preview multiple image click here
The answer of LeassTaTT works well in "standard" browsers like FF and Chrome.
The solution for IE exists but looks different. Here description of cross-browser solution:
In HTML we need two preview elements, img for standard browsers and div for IE
HTML:
<img id="preview"
src=""
alt=""
style="display:none; max-width: 160px; max-height: 120px; border: none;"/>
<div id="preview_ie"></div>
In CSS we specify the following IE specific thing:
CSS:
#preview_ie {
FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)
}
In HTML we include the standard and the IE-specific Javascripts:
<script type="text/javascript">
{% include "pic_preview.js" %}
</script>
<!--[if gte IE 7]>
<script type="text/javascript">
{% include "pic_preview_ie.js" %}
</script>
The pic_preview.js is the Javascript from the LeassTaTT's answer. Replace the $('#blah') whith the $('#preview') and add the $('#preview').show()
Now the IE specific Javascript (pic_preview_ie.js):
function readURL (imgFile) {
var newPreview = document.getElementById('preview_ie');
newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;
newPreview.style.width = '160px';
newPreview.style.height = '120px';
}
That's is. Works in IE7, IE8, FF and Chrome. Please test in IE9 and report.
The idea of IE preview was found here:
http://forums.asp.net/t/1320559.aspx
http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx
Short two-liner
This is size improvement of cmlevy answer - try
<input type=file oninput="pic.src=window.URL.createObjectURL(this.files[0])">
<img id="pic" />
I have edited #Ivan's answer to display "No Preview Available" image, if it is not an image:
function readURL(input) {
var url = input.value;
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
var reader = new FileReader();
reader.onload = function (e) {
$('.imagepreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}else{
$('.imagepreview').attr('src', '/assets/no_preview.png');
}
}
Here's a multiple files version, based on Ivan Baev's answer.
The HTML
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
JavaScript / jQuery
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
Requires jQuery 1.8 due to the usage of $.parseHTML, which should help with XSS mitigation.
This will work out of the box, and the only dependancy you need is jQuery.
Yes. It is possible.
Html
<input type="file" accept="image/*" onchange="showMyImage(this)" />
<br/>
<img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>
JS
function showMyImage(fileInput) {
var files = fileInput.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.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
You can get Live Demo from here.
Clean and simple
JSfiddle
This will be useful when you want The event to triggered indirectly from a div or a button.
<img id="image-preview" style="height:100px; width:100px;" src="" >
<input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">
<button onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>
<script type="text/javascript">
function HandleBrowseClick(hidden_input_image)
{
var fileinputElement = document.getElementById(hidden_input_image);
fileinputElement.click();
}
</script>
TO PREVIEW MULTIPLE FILES using jquery
$(document).ready(function(){
$('#image').change(function(){
$("#frames").html('');
for (var i = 0; i < $(this)[0].files.length; i++) {
$("#frames").append('<img src="'+window.URL.createObjectURL(this.files[i])+'" width="100px" height="100px"/>');
}
});
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="file" id="image" name="image[]" multiple /><br/>
<div id="frames"></div>
</body>
Example with multiple images using JavaScript (jQuery) and HTML5
JavaScript (jQuery)
function readURL(input) {
for(var i =0; i< input.files.length; i++){
if (input.files[i]) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $('<img id="dynamic">');
img.attr('src', e.target.result);
img.appendTo('#form1');
}
reader.readAsDataURL(input.files[i]);
}
}
}
$("#imgUpload").change(function(){
readURL(this);
});
}
Markup (HTML)
<form id="form1" runat="server">
<input type="file" id="imgUpload" multiple/>
</form>
In React, if the file is in your props, you can use:
{props.value instanceof File && (
<img src={URL.createObjectURL(props.value)}/>
)}
How about creating a function that loads the file and fires a custom event. Then attach a listener to the input. This way we have more flexibility to use the file, not just for previewing images.
/**
* #param {domElement} input - The input element
* #param {string} typeData - The type of data to be return in the event object.
*/
function loadFileFromInput(input,typeData) {
var reader,
fileLoadedEvent,
files = input.files;
if (files && files[0]) {
reader = new FileReader();
reader.onload = function (e) {
fileLoadedEvent = new CustomEvent('fileLoaded',{
detail:{
data:reader.result,
file:files[0]
},
bubbles:true,
cancelable:true
});
input.dispatchEvent(fileLoadedEvent);
}
switch(typeData) {
case 'arraybuffer':
reader.readAsArrayBuffer(files[0]);
break;
case 'dataurl':
reader.readAsDataURL(files[0]);
break;
case 'binarystring':
reader.readAsBinaryString(files[0]);
break;
case 'text':
reader.readAsText(files[0]);
break;
}
}
}
function fileHandler (e) {
var data = e.detail.data,
fileInfo = e.detail.file;
img.src = data;
}
var input = document.getElementById('inputId'),
img = document.getElementById('imgId');
input.onchange = function (e) {
loadFileFromInput(e.target,'dataurl');
};
input.addEventListener('fileLoaded',fileHandler)
Probably my code isn't as good as some users but I think you will get the point of it. Here you can see an example
Following is the working code.
<input type='file' onchange="readURL(this);" />
<img id="ShowImage" src="#" />
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#ShowImage')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
Try this
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("uploadImage");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
});
}
}
<input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
<div id="result" class="uploadPreview">
What about this solution?
Just add the data attribute "data-type=editable" to an image tag like this:
<img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />
And the script to your project off course...
function init() {
$("img[data-type=editable]").each(function (i, e) {
var _inputFile = $('<input/>')
.attr('type', 'file')
.attr('hidden', 'hidden')
.attr('onchange', 'readImage()')
.attr('data-image-placeholder', e.id);
$(e.parentElement).append(_inputFile);
$(e).on("click", _inputFile, triggerClick);
});
}
function triggerClick(e) {
e.data.click();
}
Element.prototype.readImage = function () {
var _inputFile = this;
if (_inputFile && _inputFile.files && _inputFile.files[0]) {
var _fileReader = new FileReader();
_fileReader.onload = function (e) {
var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
var _img = $("#" + _imagePlaceholder);
_img.attr("src", e.target.result);
};
_fileReader.readAsDataURL(_inputFile.files[0]);
}
};
//
// IIFE - Immediately Invoked Function Expression
// https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
(
function (yourcode) {
"use strict";
// The global jQuery object is passed as a parameter
yourcode(window.jQuery, window, document);
}(
function ($, window, document) {
"use strict";
// The $ is now locally scoped
$(function () {
// The DOM is ready!
init();
});
// The rest of your code goes here!
}));
See demo at JSFiddle
Preview multiple images before it is uploaded using jQuery/javascript?
This will preview multiple files as thumbnail images at a time
Html
<input id="ImageMedias" multiple="multiple" name="ImageMedias" type="file"
accept=".jfif,.jpg,.jpeg,.png,.gif" class="custom-file-input" value="">
<div id="divImageMediaPreview"></div>
Script
$("#ImageMedias").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#divImageMediaPreview");
dvPreview.html("");
$($(this)[0].files).each(function () {
var file = $(this);
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "width: 150px; height:100px; padding: 10px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
Working Demo on Codepen
Working Demo on jsfiddle
I hope this will help.
<img id="blah" alt="your image" width="100" height="100" />
<input type="file" name="photo" id="fileinput" />
<script>
$('#fileinput').change(function() {
var url = window.URL.createObjectURL(this.files[0]);
$('#blah').attr('src',url);
});
</script>
To Preview MULTIPLE Files and Single file in single function with reusable approach using Plain JavaScript
function imagePreviewFunc(that, previewerId) {
let files = that.files
previewerId.innerHTML='' // reset image preview element
for (let i = 0; i < files.length; i++) {
let imager = document.createElement("img");
imager.src = URL.createObjectURL(files[i]);
previewerId.append(imager);
}
}
<input accept="image/*" type='file' id="imageInput_1"
onchange="imagePreviewFunc(this, imagePreview_1)" />
<div id="imagePreview_1">This Div for Single Image Preview</div>
<hr />
<input class="form-control" accept="image/*" type='file' id="imageInput_2" multiple="true"
onchange="imagePreviewFunc(this, imagePreview_2)" />
<div id="imagePreview_2">This Div for Multiple Image Preview</div>
I have made a plugin which can generate the preview effect in IE 7+ thanks to the internet, but has few limitations. I put it into a github page so that its easier to get it
$(function () {
$("input[name=file1]").previewimage({
div: ".preview",
imgwidth: 180,
imgheight: 120
});
$("input[name=file2]").previewimage({
div: ".preview2",
imgwidth: 90,
imgheight: 90
});
});
.preview > div {
display: inline-block;
text-align:center;
}
.preview2 > div {
display: inline-block;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js"></script>
Preview
<div class="preview"></div>
Preview2
<div class="preview2"></div>
<form action="#" method="POST" enctype="multipart/form-data">
<input type="file" name="file1">
<input type="file" name="file2">
<input type="submit">
</form>
For Multiple image upload (Modification to the #IvanBaev's Solution)
function readURL(input) {
if (input.files && input.files[0]) {
var i;
for (i = 0; i < input.files.length; ++i) {
var reader = new FileReader();
reader.onload = function (e) {
$('#form1').append('<img src="'+e.target.result+'">');
}
reader.readAsDataURL(input.files[i]);
}
}
}
http://jsfiddle.net/LvsYc/12330/
Hope this helps someone.
It's my code.Support IE[6-9]、chrome 17+、firefox、Opera 11+、Maxthon3
function previewImage(fileObj, imgPreviewId) {
var allowExtention = ".jpg,.bmp,.gif,.png"; //allowed to upload file type
document.getElementById("hfAllowPicSuffix").value;
var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
var browserVersion = window.navigator.userAgent.toUpperCase();
if (allowExtention.indexOf(extention) > -1) {
if (fileObj.files) {
if (window.FileReader) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
};
reader.readAsDataURL(fileObj.files[0]);
} else if (browserVersion.indexOf("SAFARI") > -1) {
alert("don't support Safari6.0 below broswer");
}
} else if (browserVersion.indexOf("MSIE") > -1) {
if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
} else {//ie[7-9]
fileObj.select();
fileObj.blur();
var newPreview = document.getElementById(imgPreviewId);
newPreview.style.border = "solid 1px #eeeeee";
newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
newPreview.style.display = "block";
}
} else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
if (firefoxVersion < 7) {//firefox7 below
document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
} else {//firefox7.0+ 
document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
}
} else {
document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
}
} else {
alert("only support" + allowExtention + "suffix");
fileObj.value = ""; //clear Selected file
if (browserVersion.indexOf("MSIE") > -1) {
fileObj.select();
document.selection.clear();
}
}
}
function changeFile(elem) {
//file object , preview img tag id
previewImage(elem,'imagePreview')
}
<input type="file" id="netBarBig" onchange="changeFile(this)" />
<img src="" id="imagePreview" style="width:120px;height:80px;" alt=""/>
Default Iamge
#Html.TextBoxFor(x => x.productModels.DefaultImage, new {#type = "file", #class = "form-control", onchange = "openFile(event)", #name = "DefaultImage", #id = "DefaultImage" })
#Html.ValidationMessageFor(model => model.productModels.DefaultImage, "", new { #class = "text-danger" })
<img src="~/img/ApHandler.png" style="height:125px; width:125px" id="DefaultImagePreview"/>
</div>
<script>
var openFile = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
var dataURL = reader.result;
var output = document.getElementById('DefaultImagePreview');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
</script>
Here's a solution if you're using React:
import * as React from 'react'
import { useDropzone } from 'react-dropzone'
function imageDropper() {
const [imageUrl, setImageUrl] = React.useState()
const [imageFile, setImageFile] = React.useState()
const onDrop = React.useCallback(
acceptedFiles => {
const file = acceptedFiles[0]
setImageFile(file)
// convert file to data: url
const reader = new FileReader()
reader.addEventListener('load', () => setImageUrl(String(reader.result)), false)
reader.readAsDataURL(file)
},
[setImageFile, setImageUrl]
)
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop })
return (
<div>
<div {...getRootProps()}>
{imageFile ? imageFile.name : ''}
{isDragActive ? <p>Drop files here...</p> : <p>Select image file...</p>}
<input {...getInputProps()} />
</div>
{imageUrl && (
<div>
Your image: <img src={imageUrl} />
</div>
)}
</div>
)
}
https://stackoverflow.com/a/59985954/8784402
ES2017 Way
// convert file to a base64 url
const readURL = file => {
return new Promise((res, rej) => {
const reader = new FileReader();
reader.onload = e => res(e.target.result);
reader.onerror = e => rej(e);
reader.readAsDataURL(file);
});
};
// for demo
const fileInput = document.createElement('input');
fileInput.type = 'file';
const img = document.createElement('img');
img.attributeStyleMap.set('max-width', '320px');
document.body.appendChild(fileInput);
document.body.appendChild(img);
const preview = async event => {
const file = event.target.files[0];
const url = await readURL(file);
img.src = url;
};
fileInput.addEventListener('change', preview);
Here is a much easy way to preview image before upload using pure javascript;
//profile_change is the id of the input field where we choose an image
document.getElementById("profile_change").addEventListener("change", function() {
//Here we select the first file among the selected files.
const file = this.files[0];
/*here i used a label for the input field which is an image and this image will
represent the photo selected and profile_label is the id of this label */
const profile_label = document.getElementById("profile_label");
//Here we check if a file is selected
if(file) {
//Here we bring in the FileReader which reads the file info.
const reader = new FileReader();
/*After reader loads we change the src attribute of the label to the url of the
new image selected*/
reader.addEventListener("load", function() {
dp_label.setAttribute("src", this.result);
})
/*Here we are reading the file as a url i.e, we try to get the location of the
file to set that as the src of the label which we did above*/
reader.readAsDataURL(file);
}else {
//Here we simply set the src as default, whatever you want if no file is selected.
dp_label.setAttribute("src", "as_you_want")
}
});
And here is the HTML;
<label for="profile_change">
<img title="Change Profile Photo" id="profile_label"
src="as_you_want" alt="DP" style="height: 150px; width: 150px;
border-radius: 50%;" >
</label>
<input style="display: none;" id="profile_change" name="DP" type="file" class="detail form-control">
for my app, with encryped GET url parameters, only this worked. I always got a TypeError: $(...) is null.
Taken from https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
function assignFilePreviews() {
$('input[data-previewable=\"true\"]').change(function() {
var prvCnt = $(this).attr('data-preview-container');
if (prvCnt) {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var img = $('<img>');
img.attr('src', e.target.result);
img.error(function() {
$(prvCnt).html('');
});
$(prvCnt).html('');
img.appendTo(prvCnt);
}
reader.readAsDataURL(this.files[0]);
}
}
});
}
$(document).ready(function() {
assignFilePreviews();
});
HTML
<input type="file" data-previewable="true" data-preview-container=".prd-img-prv" />
<div class = "prd-img-prv"></div>
This also handles case when file with invalid type ( ex. pdf ) is choosen

Getting details selected images in php

I'm using html5 js to upload multiple images. Why when we upload multiple images does the result (PHP: print_r($_FILES['upimg']['name'])) only shows details of the last selected image?
For Example:(i selected following image name)
111111.gif
222222.gif
333333.gif
PHP code only last selected image show: 333333.gif
But I want to show details from all the images.
What do I do?
DEMO: http://codepad.viper-7.com/16abeG
FULL CODE:
<!doctype html>
<html>
<head>
<?php
if($_FILES){
echo '<pre>';
print_r($_FILES['upimg']['name']);
//for($i=0; $i<count($_FILES['name']); $i++){
//if ($_FILES['error'][$i] == 0) {
////do your stuff here, each image is at $_FILES['tmp_name'][$i]
//}
//}
}
?>
<title>file input click() demo</title>
<script type="text/javascript">
function doClick() {
var el = document.getElementById("fileElem");
if (el) {
el.click();
}
}
function handleFiles(files) {
var d = document.getElementById("fileList");
if (!files.length) {
d.innerHTML = "<p>No files selected!</p>";
} else {
var list = document.createElement("ul");
d.appendChild(list);
for (var i=0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var img = document.createElement("img");
img.src = window.URL.createObjectURL(files[i]);;
img.height = 60;
img.onload = function() {
window.URL.revokeObjectURL(this.src);
}
li.appendChild(img);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
}
}
</script>
</head>
<body>
<p>This is a demo of calling <code>click()</code> on a form's file picker.
Note that the file input element is actually hidden here, so the
user doesn't have to see the path to the selected file.</p>
Select some files
<div id="fileList">
<p>No files selected!</p>
</div>
<form action="#" method="post" enctype="multipart/form-data">
<input name="upimg[]" type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<input type="submit" value="Click to see the result">
</form>
</body>
</html>
Your logic i think is wrong you use HTML 5, but not upload images via AJAX you use form for this method.
Miltiple is only HTML 5 and you can't use for PHP purpose without AJAX.
I created similar plugin you can check : https://github.com/dimitardanailov/js-control-files-uploader
Try wrapping it in a for loop somewhat like the code you have commented out....
if(isset($_FILES["upimg"]["name"])) {
for($i=0; $i<count($_FILES["upimg"]["name"]);$i++) {
echo $_FILES["upimg"]["name"][$i];
}
}
why don't you use tag before any of the .parent div?
for width ratio you of course can do it using jquery.
myElement.width = (parentElement.width/100)*40

PHP AJAX Image Upload Example Not Uploading

My code produces no errors on the console. When I click the upload button, nothing happens. There is a post sent to itself, as instructed in the tutorial I used but the image is not uploaded to my folder and it is not displayed on my page. Barring the fact I know I should use jquery (I will make the transition once I get it to upload to the folder) what is wrong with my code?
<?php
if (!empty($_FILES)) {
$name = $_FILES['file']['name'];
if ($_FILES['file']['error'] == 0) {move_uploaded_file($_FILES['file']
['tmp_name'], "post_images/" . $name))}
}
?>
<script type="text/javascript">
var handleUpload = function (event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('file', fileInput.files[1]);
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if (event.lengthComputable)
{
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes()) {
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +
'%'));
}
});
request.upload.addEventListener('load',function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Upload failed');
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
};
window.addEventListener('load', function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
</script>
<div id="uploaded">
<?php
if (!empty($name)) {
echo '<img src="post_images/' . $name . '" width="100" height="100" />';
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="file" name="file" />
<input type="submit" id="submit" value="upload" />
</div>
</form>
</div>
There is only one file in a non- multiple file input element, fileInput.files[1] attempts to use the second file.
data.append('file', fileInput.files[0]);

php code to call javascript function returns function is not defined

The code bellow tries to ask the user to upload kml file and then saves the file at the same time it shows the kml data in google maps using google maps api v2. I could successfully take the kml file and saves it at a specific directory, HOWEVER, i am facing some problem in displaying the file on google maps immediately after the user clicks on KML TEST button. The error is Uncaught ReferenceError: showKML is not defined
Here is the code that I used
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Find latitude and longitude with Google Maps</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAgrj58PbXr2YriiRDqbnL1RSqrCjdkglBijPNIIYrqkVvD1R4QxRl47Yh2D_0C1l5KXQJGrbkSDvXFA"
type="text/javascript"></script>
<?php
$upload = $_SERVER['PHP_SELF'];
if(isset($_POST['kmltest'])) {
$target_path = "uploads/";
$fn = basename( $_FILES['uploadedfile']['name']);
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
//echo $target_path ;
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
echo "<script type=\"text/javascript\"> showKML(); </script>";
}
else{
echo "There was an error uploading the file, please try again!";
}
}
?>
<script src="egeoxml.js" type="text/javascript"></script>
<script type="text/javascript">
var map;
var options = {};
var shapeCounter_ = 0;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(25.22903, 55.46612), 13);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.clearOverlays();
document.getElementById("lat").value = "25.22903";
document.getElementById("lng").value = "55.46612";
}
}
function startShape() {
initialize();
document.getElementById('lat').disabled = true;
document.getElementById('lng').disabled = true;
var polygon = new GPolygon([],"ff0000", 2, 0.7,"ff0000",0.2);
startDrawing(polygon, "Shape " + (++shapeCounter_), function() {
var cell = this;
var area = polygon.getArea();
cell.innerHTML = (Math.round(area / 10000) / 100) + "km<sup>2</sup>";
});
showcoor(polygon);
}
function startDrawing(poly, name, onUpdate) {
map.addOverlay(poly);
poly.enableDrawing(options);
poly.enableEditing({onEvent: "mouseover"});
poly.disableEditing({onEvent: "mouseout"});
GEvent.addListener(poly, "endline", function() {
GEvent.addListener(poly, "click", function(latlng, index) {
if (typeof index == "number") {
poly.deleteVertex(index);
}
});
});
}
function showcoor (poly) {
GEvent.addListener(poly, "endline", function() {
GEvent.addListener(poly, "click", function() {
var str= "" ;
for (var i = 0, I = this.getVertexCount(); i < I; ++i) {
var xy = this.getVertex(i);
str += xy.lat() + ', ' + xy.lng() + '<br />';
}
alert (str);
});
});
}
function drawpoint() {
//initialize();
document.getElementById('lat').disabled = false;
document.getElementById('lng').disabled = false;
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
var center = new GLatLng(parseFloat(lat), parseFloat (lng));
map.setCenter(center, 7);
geocoder = new GClientGeocoder();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
GEvent.addListener(marker, "dragend", function() {
var point = marker.getPoint();
map.panTo(point);
document.getElementById("lat").value = center.lat().toFixed(5);
document.getElementById("lng").value = center.lat().toFixed(5);
});
GEvent.addListener(map, "moveend", function() {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").value = center.lat().toFixed(5);
document.getElementById("lng").value = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function() {
var point =marker.getPoint();
map.panTo(point);
document.getElementById("lat").value = point.lat().toFixed(5);
document.getElementById("lng").value = point.lng().toFixed(5);
});
});
}
function showKML() {
//alert(filename);
initialize();
document.getElementById('lat').disabled = true;
document.getElementById('lng').disabled = true;
var exml;
exml = new EGeoXml("exml", map, ("uploads/test.kml"));
exml.parse();
exml.show();
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()" >
<form action = <?php echo $upload; ?> method = "post" enctype="multipart/form-data"/>
<p align="left">
<table>
<tr>
<td><b>Latitude</b></td>
<td><b>Longitude</b></td>
</tr>
<tr>
<td>
<input type="text" name="lat" id="lat" /></td>
<td>
<input type="text" name="lng" id="lng" /></td>
<td>
<input type="button" name="point" id="point" value="Point" onclick="drawpoint()" /><td>
<input type="button" name="shape_b" id="shape_b" value="Poly" onclick="startShape()" /><td>
<input type="submit" name="kmltest" id="kmltest" value="KML TEST" /> </td></tr>
<tr>
<td>
<input type="file" name="uploadedfile" id="uploadedfile" />
</td>
</tr>
</table>
</p>
<p>
<div align="center" id="map" style="width: 600px; height: 400px"><br/></div>
</p>
<script type="text/javascript">
//<![CDATA[
if (typeof _gstat != "undefined") _gstat.audience('','pagesperso-orange.fr');
//]]>
</script>
</form>
</body>
</html>
your assistance is highly appreciated
JavaScript <script> blocks are evaluated in blocks.
Within the same block, a function can be called before it's defined, because function declarations are evaluated before the rest of the code.
However, when you move function showKML(){} to a different block, the function is called before it's defined, hence the error.
To solve the problem, you have to move the function declaration before the <?php .. ?> block, where showKML is called.
A JSFiddle to demonstrate the problem: http://jsfiddle.net/SGbfu/1/
More detailled explanation:
When <script> and </script> is encountered, the code between is directly evaluated.
All functions, declared using function x(){} are evaluated first. Then, the rest of the code is considered.
Step 1-2 is repeated, till all <script> blocks in the document are evaluated.
Example:
<script>
f(); // No error, f is declared below
function f(){ alert('f() called'); }
g(); // Error: g is not defined before, or within this block
</script>
<script>
function g(){}
</script>
you need to move the <script> block with the function definitions to the top. At the time you call the function showKML() its not yet defined. You should bind showKML() to the document ready event. (e.g. put the function call inside your initialize() function that is already called on the page load event)
Also i suggest you move the javascript code definition to an external file and include it just like you include the google maps API - this avoids loading the code with each page refresh and reduces traffic and page load.

Categories