I have validation in my angular controller to validate a image is a set size and is 1080x1920.
however evry image i try and upload I get error message
Error Uploading the image, make sure the resolution is 1080x1920px
even when I upload a image of the correct size. I am woundering if someone can spot a error in my code of why that may be ?
HTML
<div ng-controller="UpLoadImage">
<div ng-repeat="step in stepsModel">
<img class="thumb" ng-src="{{step}}"/>
</div>
<label for="file">Select File</label>
<input ng-model="file" type='file' name='file' id='fileinput' base-sixty-four-input required onload='onLoad' maxsize='600'
accept='image/*' onchange='angular.element(this).scope().imageUpload(this)'/>
{{uploadError}}
<button>Add to array</button>
JavaScript
.controller('UpLoadImage', function ($scope, $http, $timeout) {
$scope.imageUpload = function(){
//
// $scope.uploadBtn = false;
$scope.errorActive = false;
$scope.success = false;
$scope.newImage = false;
var reader = new FileReader();
var input, file;
if (!window.FileReader) {
alert("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
$scope.errorActive = true;
$scope.uploadError = "Um, couldn't find the file input element.";
$scope.$apply();
}
else if (!input.files) {
$scope.errorActive = true;
$scope.uploadError = "This browser doesn't seem to support the `files` property of file inputs.";
$scope.$apply();
}
else if (!input.files[0]) {
$scope.errorActive = true;
$scope.uploadError = "Please select a file before clicking 'Upload'";
$scope.$apply();
}
else {
file = input.files[0];
size = file.size;
if(size < 650000){
var fr = new FileReader;
fr.onload = function(e){
var img = new Image;
img.onload = function(){
var width = img.width;
var height = img.height;
if(width == 1080 && height == 1920){
$scope.uploadError = '';
$scope.errorActive = false;
$scope.playingNow.background = e.target.result;
$scope.newImage = true;
$scope.uploadError = 'image uploaded';
$scope.$apply();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(element.files[0]);
}else{
$scope.errorActive = true;
$scope.uploadError = 'Error Uploading the image, make sure the resolution is 1080x1920px';
$scope.$apply();
}
};
img.src = fr.result;
};
fr.readAsDataURL(file);
}else{
$scope.errorActive = true;
$scope.uploadError = 'max file size supported is 650Kb please compress your image';
}
}
$scope.$apply();
};
$scope.imageIsLoaded = function (e) {
$scope.$apply(function () {
$scope.stepsModel.push(e.target.result);
});
$scope.onLoad = function (e, reader, file, fileList, fileOjects, fileObj) {
};
};
$scope.stepsModel = [];
})
As you are getting width = 1920 and height = 1080 so change your if condition :
if(height=== 1080 && width=== 1920){
// your code
}
if(width == "1080" && height == "1920"){
This should fix it.
Related
I got this code from a website and applied to my code:
window.onload = function () {
var fileUpload = document.getElementById("fileupload");
fileUpload.onchange = function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = document.getElementById("dvpreview");
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png)$/;
for (var i = 0; i < fileUpload.files.length; i++) {
var file = fileUpload.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.width="300";
img.height ="300";
img.src = e.target.result;
dvPreview.appendChild(img);
}
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
}
}
};
It works properly, but I want some more style to be added to my code. Specially the padding and the object-fit css properties.
I tried to run:
img.objectFit="cover";
img.style.objectFit="cover";
img.css("object-fit","cover");
and a lot more possibilities that i could search and apply, but any of those worked out.
What is the right way to make this work?
var img = document.createElement('img');
img.width = '300';
img.height = '300';
img.style.padding = '20px';
img.style.objectFit = 'fill';
document.body.appendChild(img);
I have a function that displays a selected image along with the image width and height. I would like to put in a check to alert if the image dimensions are greater that 390x390. I have marked the place I think a size check should go, I may be wrong. But it does not work anyway.
If someone has time you they please take a look to see how I should be dong the size check.
Many thanks in advance for your time.
My script:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("image_field"),
elPreview = document.getElementById("preview2"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
function readImage (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.addEventListener("load", function () {
var imageInfo = '<br><br>Your selected file size is<br> Display width ' +
image.width + ', Display height ' +
image.height + ' ' + '';
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
if (useBlob) {
window.URL.revokeObjectURL(file);
}
});
reader.readAsDataURL(file);
}
elBrowse.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
// SOMETHING LIKE THIS
if( (image.width < 390 && image.height < 390) .test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Selected image is to small\n";
}
// END
}
}
if (errors) {
alert(errors);
}
});
so you need to move the checking to the event listener because that's the first place where you can know the image resolution
here you don't have the errors list, so you need to modify it a bit yet, but you can start from here:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("image_field"),
elPreview = document.getElementById("preview2"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
function readImage (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.addEventListener("load", function () {
if(image.width <= 390 && image.height <= 390)
{
var imageInfo = '<br><br>Your selected file size is<br> Display width ' +
image.width + ', Display height ' +
image.height + ' ' + '';
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
} else {
alert ( file.name +" Selected image is to big\n");
}
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
if (useBlob) {
window.URL.revokeObjectURL(file);
}
});
reader.readAsDataURL(file);
}
elPreview.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
if (errors) {
alert(errors);
}
});
for the file variable (on the first place you aimed to check the dimensions, you can only base your condition on the file size - in bytes)
I'm not sure if I understood the question, but did you mean something like this?
elBrowse.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
if(image.width <= 390 && image.height <= 390)
{
readImage( file );
} else {
errors += file.name +" Selected image is to big\n";
}
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
if (errors) {
alert(errors);
}
});
Loading the image and getting the dimension is async, so you can't use the check inside the for loop, it has do be done inside the callback
(unless you are using async/await or generators+yield)
var elBrowse = document.getElementById('image_field')
var elPreview = document.getElementById('preview2')
// No point in addthing the listener if we can't read them anyway
if ('files' in elBrowse) {
// No need for addEventListener if you only going to have 1 listener
elBrowse.onchange = () => {
for (let file of elBrowse.files) {
file.image().then(image => {
// Now if you don't like the extension you can always transform it
// using the canvas element...
if (image.width < 390 && image.height < 390)
return console.error(file.name + ' is to small\n')
let info = `<br><br>${file.name} size is ${file.size} bytes
and dimension is ${image.width}x${image.height}<br>`
elPreview.appendChild(image)
elPreview.insertAdjacentHTML('beforeend', info)
}, err => {
console.error(file.name + " Isn't an image")
})
}
}
} else {
console.info('reading the file is not possible, use flash alternetive?')
}
<!--
Getting a bit of help from Screw-FileReader
ref: https://github.com/jimmywarting/Screw-FileReader
-->
<script src="https://cdn.rawgit.com/jimmywarting/Screw-FileReader/master/index.js"></script>
<!--
use the accept attribute to say that you only want images
So you don't have to check for it in your code
But for just in case we listen for image.onerror when we load the image
-->
<input id=image_field type=file multiple accept="image/*">
<div id=preview2>
I have a page with four images for the user to select. I want the user to be able to preview each image on the site before upload.
The JavaScript code below works for only one image but I would like it to work for multiple images uploaded via <input type="file">.
What will be the best way to do this?
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#output').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#file-input").change(function () {
readURL(this);
});
Here is jQuery version for you. I think it more simplest thing.
$(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');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
Add the multiple attribute to your HTMLInputElement
Add the accept attribute to your HTMLInputElement
To filter your files selection to images only, use accept="image/*", or a comma separated MIME list: accept="image/png, image/jpeg"
Use FileReader.readAsDataURL to get the Base64 string,
or URL.createObjectURL to get the file Blob object
Using FileReader.readAsDataURL
The asynchronous way to read the image data is by using FileReader API and its readAsDataURL method which returns a Base64 String:
const preview = (file) => {
const fr = new FileReader();
fr.onload = () => {
const img = document.createElement("img");
img.src = fr.result; // String Base64
img.alt = file.name;
document.querySelector('#preview').append(img);
};
fr.readAsDataURL(file);
};
document.querySelector("#files").addEventListener("change", (ev) => {
if (!ev.target.files) return; // Do nothing.
[...ev.target.files].forEach(preview);
});
#preview img { max-height: 100px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
Async strategy:
Due to the asynchronous nature of FileReader, you could implement an async/await strategy:
// DOM utility functions:
const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, props) => Object.assign(document.createElement(tag), props);
// Preview images before upload:
const elFiles = el("#files");
const elPreview = el("#preview");
const previewImage = (props) => elPreview.append(elNew("img", props));
const reader = (file, method = "readAsDataURL") => new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onload = () => resolve({ file, result: fr.result });
fr.onerror = (err) => reject(err);
fr[method](file);
});
const previewImages = async(files) => {
// Remove existing preview images
elPreview.innerHTML = "";
let filesData = [];
try {
// Read all files. Return Array of Promises
const readerPromises = files.map((file) => reader(file));
filesData = await Promise.all(readerPromises);
} catch (err) {
// Notify the user that something went wrong.
elPreview.textContent = "An error occurred while loading images. Try again.";
// In this specific case Promise.all() might be preferred over
// Promise.allSettled(), since it isn't trivial to modify a FileList
// to a subset of files of what the user initially selected.
// Therefore, let's just stash the entire operation.
console.error(err);
return; // Exit function here.
}
// All OK. Preview images:
filesData.forEach(data => {
previewImage({
src: data.result, // Base64 String
alt: data.file.name // File.name String
});
});
};
elFiles.addEventListener("change", (ev) => {
if (!ev.currentTarget.files) return; // Do nothing.
previewImages([...ev.currentTarget.files]);
});
#preview img { max-height: 100px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
Using URL.createObjectURL
The synchronous way to read the image is by using the URL API and its createObjectURL method which returns a Blob:
const preview = (file) => {
const img = document.createElement("img");
img.src = URL.createObjectURL(file); // Object Blob
img.alt = file.name;
document.querySelector('#preview').append(img);
};
document.querySelector("#files").addEventListener("change", (ev) => {
if (!ev.target.files) return; // Do nothing.
[...ev.target.files].forEach(preview);
});
#preview img { max-height: 120px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
Although looks much simpler, it has implications on the main thread due to its synchronicity, and requires you to manually use (when possible) URL.revokeObjectURL in order to free up memory:
// Remove unused images from #preview? Consider also using
URL.revokeObjectURL(someImg.src); // Free up memory space
jQuery example:
A jQuery implementation of the above FileReader.readAsDataURL() example:
const preview = (file) => {
const fr = new FileReader();
fr.onload = (ev) => {
$('#preview').append($("<img>", {src: fr.result, alt: file.name}));
};
fr.readAsDataURL(file);
};
$("#files").on("change", (ev) => {
if (!ev.target.files) return; // Do nothing.
[...ev.target.files].forEach(preview);
});
#preview img { max-height: 120px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
Additional read:
File API — Using files from web applications (MDN)
readAsDataURL (MDN)
FileReader result (MDN)
Promise.all() (MDN)
Preview Image, get file size, image height and width before upload
Tips:
Besides using the HTMLInputElement attribute accept, if you want to make sure within JavaScript that a file is-of-type, you could:
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
// Not a valid image
}
or like:
if (!/^image\//i.test(file.type)) {
// File is not of type Image
}
function previewMultiple(event){
var saida = document.getElementById("adicionafoto");
var quantos = saida.files.length;
for(i = 0; i < quantos; i++){
var urls = URL.createObjectURL(event.target.files[i]);
document.getElementById("galeria").innerHTML += '<img src="'+urls+'">';
}
}
#galeria{
display: flex;
}
#galeria img{
width: 85px;
height: 85px;
border-radius: 10px;
box-shadow: 0 0 8px rgba(0,0,0,0.2);
opacity: 85%;
}
<input type="file" multiple onchange="previewMultiple(event)" id="adicionafoto">
<div id="galeria">
</div>
Just use FileReader.readAsDataURL()
HTML:
<div id='photos-preview'></div>
<input type="file" id="fileupload" multiple (change)="handleFileInput($event.target.files)" />
JS:
function handleFileInput(fileList: FileList) {
const preview = document.getElementById('photos-preview');
Array.from(fileList).forEach((file: File) => {
const reader = new FileReader();
reader.onload = () => {
var image = new Image();
image.src = String(reader.result);
preview.appendChild(image);
}
reader.readAsDataURL(file);
});
}
DEMO
$(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');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
function previewImages() {
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
<input id="file-input" type="file" multiple>
<div id="preview"></div>
function previewImages() {
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
<input id="file-input" type="file" multiple>
<div id="preview"></div>
<script type="text/javascript">
var upcontrol = {
queue : null, // upload queue
now : 0, // current file being uploaded
start : function (files) {
// upcontrol.start() : start upload queue
// WILL ONLY START IF NO EXISTING UPLOAD QUEUE
if (upcontrol.queue==null) {
// VISUAL - DISABLE UPLOAD UNTIL DONE
upcontrol.queue = files;
document.getElementById('uploader').classList.add('disabled');
// PREVIEW UPLOAD IMAGES
upcontrol.preview();*enter code here*
//PROCESS UPLOAD ON CLICK
$('#add_files').on('click', function() {
upcontrol.run();
});
}
},
preview : function() {
//upcontrol.preview() : preview uploading file
if (upcontrol.queue) {
var filesAmount = upcontrol.queue.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
var fimg = document.createElement('img')
fimg.src = event.target.result,
fimg.classList = "col-sm-6 col-md-6 col-lg-4 float-left center",
document.getElementById('gallery').appendChild(fimg);
}
reader.readAsDataURL(upcontrol.queue[i]);
}
}
},
run : function () {
// upcontrol.run() : proceed upload file
var xhr = new XMLHttpRequest(),
data = new FormData();
data.append('file-upload', upcontrol.queue[upcontrol.now]);
xhr.open('POST', './lockeroom/func/simple-upload.php', true);
xhr.onload = function (e) {
// SHOW UPLOAD STATUS
var fstat = document.createElement('div'),
txt = upcontrol.queue[upcontrol.now].name + " - ";
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// SERVER RESPONSE
txt += xhr.responseText;
} else {
// ERROR
txt += xhr.statusText;
}
}
fstat.innerHTML = txt;
document.getElementById('upstat').appendChild(fstat);
// UPLOAD NEXT FILE
upcontrol.now++;
if (upcontrol.now < upcontrol.queue.length) {
upcontrol.run();
}
// ALL DONE
else {
upcontrol.now = 0;
upcontrol.queue = null;
document.getElementById('uploader').classList.remove('disabled');
}
};
xhr.send(data);
}
};
window.addEventListener("load", function () {
// IF DRAG-DROP UPLOAD SUPPORTED
if (window.File && window.FileReader && window.FileList && window.Blob) {
/* [THE ELEMENTS] */
var uploader = document.getElementById('uploader');
/* [VISUAL - HIGHLIGHT DROP ZONE ON HOVER] */
uploader.addEventListener("dragenter", function (e) {
e.preventDefault();
e.stopPropagation();
uploader.classList.add('highlight');
});
uploader.addEventListener("dragleave", function (e) {
e.preventDefault();
e.stopPropagation();
uploader.classList.remove('highlight');
});
/* [UPLOAD MECHANICS] */
// STOP THE DEFAULT BROWSER ACTION FROM OPENING THE FILE
uploader.addEventListener("dragover", function (e) {
e.preventDefault();
e.stopPropagation();
});
// ADD OUR OWN UPLOAD ACTION
uploader.addEventListener("drop", function (e) {
e.preventDefault();
e.stopPropagation();
uploader.classList.remove('highlight');
upcontrol.start(e.dataTransfer.files);
});
}
// FALLBACK - HIDE DROP ZONE IF DRAG-DROP UPLOAD NOT SUPPORTED
else {
document.getElementById('uploader').style.display = "none";
}
});
</script>
i used somthing like this and i got the best result and easy to understand.
function appendRows(){
$i++;
var html='';
html+='<div id="remove'+$i+'"><input type="file" name="imagefile[]" accept="image/*" onchange="appendloadFile('+$i+')"><img id="outputshow'+$i+'" height="70px" width="90px"><i onclick="deleteRows('+$i+')" class="fas fa-trash-alt"></i></div>';
$("#appendshow").append(html);
}
function appendloadFile(i){
var appendoutput = document.getElementById('outputshow'+i+'');
appendoutput.src = URL.createObjectURL(event.target.files[0]);
}
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);
$(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');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery">
$(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');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery">
Hi I am having proble while downloading the image from image tag, I have googled it but not getting any valid solutions. Can anyone help to get solve this..
Actually I am binding some bytestring to the image tag src like this
<img src="' + this.el.toDataURL("image/png") +'" class="img-responsive imgSmall" style="background-color:green;" alt="img" data-position-to="origin" data-transition="slide" id="signPrevwID_' + signatureid +'">
and I am downloading the the same image with background color green but its not working,everytime its saving with background color black only, for downloading Im using this code
var bannerImage = document.getElementById('signPrevwID_' + signatureid );
var imgData = getBase64Image(bannerImage);
console.log("imgData - "+imgData);
//alert("imgData - "+imgData);
var newName = 'Test_' + new Date().getTime()+".png";
var fileWritter = new AppUtils.FileWritter(newName);
fileWritter.saveBase64ToBinary(imgData, function(r){
console.log("saveBase64ToBinary() file saved");
}, function(e){
console.log("saveBase64ToBinary() file not saved");
});
var AppUtils2 = (function(){
//alert("AppUtils2");
// get the application directory. in this case only checking for Android and iOS
function localFilePath(filename) {
if(device.platform.toLowerCase() === 'android') {
return cordova.file.externalRootDirectory + filename;
} else if(device.platform.toLowerCase() == 'ios') {
return cordova.file.externalRootDirectory + filename;
}
}
// FileWritter class
function FileWritter(filename) {
//deleteStoredFromDevice(filename);
this.fileName = filename;
this.filePath = localFilePath(filename);
alert("fileName - "+fileName);
}
// decode base64 encoded data and save it to file
FileWritter.prototype.saveBase64ToBinary = function(data, ok, fail) {
var byteData = atob(data);
var byteArray = new Array(byteData.length);
for (var i = 0; i < byteData.length; i++) {
byteArray[i] = byteData.charCodeAt(i);
}
var binaryData = (new Uint8Array(byteArray)).buffer;
// createDirectory();
this.saveFile(binaryData, ok, fail);
}
// save file to storage using cordova
FileWritter.prototype.saveFile = function(data, ok, fail) {
this.fileData = data;
var path = this.filePath.substring(0, this.filePath.lastIndexOf('/'));
//console.log("saveFile() path - "+path);
var that = this;
// Write file on local system
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory+"Download/Mobitrac/Docs", function(directoryEntry) {
var options = {create: true, exclusive: false};
alert("that.fileName - "+cordova.file.externalRootDirectory+"Download/Mobitrac/Docs");
directoryEntry.getFile(that.fileName, options, function(file) {
alert("that.fileName - "+that.fileName);
file.createWriter(function(writer) {
writer.onwriteend = function(event) {
if(typeof ok === 'function') {
alert("onwriteend");
//viewing documents locally
//var fileWritter = new AppUtils.viewFile(subEventId+'.'+fileExtention);
ok(event);
}
};
writer.write(that.fileData);
}, fail);
}, fail);
}, fail);
};
/*// open InApp Browser to view file
function viewFile(filename) {
//var path = localFilePath(filename);
var path = cordova.file.externalRootDirectory+"Download/Mobitrac/Docs/"+filename;
alert("viewFile() path - - "+path);
window.open(path, "_system", "location=yes,hidden=no,closebuttoncaption=Close");
}
return {
FileWritter: FileWritter,
localFilePath: localFilePath,
viewFile: viewFile
}*/
})();
var fileExtention = '';
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
console.log("data - "+dataURL);
return dataURL.replace(/^data:image\/(png);base64,/, "");
}
Byte string im getting with sketch.js canvas element, I mean Im drawing something on canvas and appening same image to the img tag in html with background color green.
I am not getting from where its breaking, please anybody help me
This is the first time I am working with JavaScript modules. I am trying to upload an image and show it in a div under 'id="imageholder"'.
The error is:
uncaught type error :can't find property 'fileread' of undefined
HTML:
<html>
<body>
<div id='imageholder' style='width:100px;height:100px;border:1px solid black;position:relative;left:100px;'></div>
<input type='file' id='up' />
<script src='myscript.js'></script>
<script>
document.getElementById('up').addEventListener('change', FileUpload.files, false);
</script>
</body>
</html>
Here is the myscript.js module file which should return the object called FileUpload. But error is saying it is undefined. Why it is
undefined? It is long but it works when I don't use it like a module but all in a single file.
You can jump at the end and can see I am returning an object literal to FileUpload variable.
var FileUpload = (function(fileElement) {
var imageholder = document.getElementById('imageholder');
function getBLOBFileHeader(url, blob, callback, callbackTwo) {
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
console.log(header);
var imgtype = callback(url, header); // headerCallback
callbackTwo(imgtype, blob)
};
fileReader.readAsArrayBuffer(blob);
}
function headerCallback(url, headerString) {
var info = getHeaderInfo(url, headerString);
return info;
}
function getTheJobDone(mimetype, blob) {
var mimearray = ['image/png', 'image/jpeg', 'image/gif'];
if (mimearray.indexOf(mimetype) != -1) {
printImage(blob);
} else {
fileElement.value = '';
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
// alert('you can not upload this file type');
}
}
function remoteCallback(url, blob) {
getBLOBFileHeader(url, blob, headerCallback, getTheJobDone);
}
function printImage(blob) {
// Add this image to the document body for proof of GET success
var fr = new FileReader();
fr.onloadend = function(e) {
var img = document.createElement('img');
img.setAttribute('src', e.target.result);
img.setAttribute('style', 'width:100%;height:100%;');
imageholder.appendChild(img);
};
fr.readAsDataURL(blob);
}
function mimeType(headerString) {
switch (headerString) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
type = "image/jpeg";
break;
default:
type = "image/pjpeg";
break;
}
return type;
}
function getHeaderInfo(url, headerString) {
return (mimeType(headerString));
}
// Check for FileReader support
function fileread(event) {
if (window.FileReader && window.Blob) {
/* Handle local files */
var mimetype;
var mimearray = ['image/png', 'image/jpeg', 'image/gif'];
var file = event.target.files[0];
if (mimearray.indexOf(file.type) === -1 || file.size >= 2 * 1024 * 1024) {
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
fileElement.value = '';
file = null;
return false;
} else {
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
remoteCallback(file.name, file);
}
} else {
// File and Blob are not supported
console.log('file and blob is not supported');
}
}
return {
files: fileread
};
}(document.getElementById('up')))
it's working right as you provided it jsfiddle.net/fredo5n8/ here is the proof.
Are you sure you did not forget to wipe cache in your browser? If that's the case, try to run the code in incognito (private) window.
EDIT:
<html>
<body>
<div id='imageholder' style='width:100px;height:100px;border:1px solid black;position:relative;left:100px;'></div>
<input type='file' id='up' />
<script id='myscript' src='myscript.js'></script>
<script>
var script = document.getElementById('myscript');
var attachInputEvents = function () {
document.getElementById('up').addEventListener('change', FileUpload.files, false);
}
script.onload=attachInputEvents();
</script>
</body>
</html>
This way, you'll wait for the srcript to load(I guess that's the problem, cause locally on my machine even with separate files, it worked good hosted on WAMP server)