I have figured out how to preload images. What I am trying to find out now is whether there is any way, using Javascript, to get the local filepath where an image has been cached.
You can use a combination of FileReader and sessionStorage.
Something like:
var input = document.querySelector("#imageInput");
input.addEventListener("change", function(e){
var reader = new FileReader();
reader.onload = function(evt){
var newImage = document.createElement("img");
newImage.src = evt.target.result;
document.querySelector("body").appendChild(newImage);
sessionStorage.setItem("image", evt.target.result);
};
reader.readAsDataURL(e.target.files[0]);
}, false);
window.addEventListener("load", function(e){
if(sessionStorage.getItem("image")){
var newImage = document.createElement("img");
newImage.src = sessionStorage.getItem("image");
document.querySelector("body").appendChild(newImage);
}
}, false);
That would store all of your images on the browser and have them persist through posts and reloads. Then you can add any logic to edit them as you need.
Unfortunately, you can't set inputs of type "file" so you'll need to do some UI magic.
Related
I'd like to change the URLs from data:image base64 to blob. This is the original code that produces the base64 urls:
<script>
$(window).load(function(){
function readURL() {
var $input = $(this);
var $newinput = $(this).parent().parent().parent().find('.portimg ');
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
reset($newinput.next('.delbtn'), true);
$newinput.attr('src', e.target.result).show();
$newinput.after('<div class="delbtn delete_upload" title="Remove"><span class="bbb-icon bbb-i-remove2"></span></div>');
$("form").on('click', '.delbtn', function (e) {
reset($(this));
$("form").find('#rright-<?php echo $i;?>').hide();
});
}
reader.readAsDataURL(this.files[0]);
}
}
$(".file").change(readURL);
function reset(elm, prserveFileName) {
if (elm && elm.length > 0) {
var $input = elm;
$input.prev('.portimg').attr('src', '').hide();
if (!prserveFileName) {
$($input).parent().parent().parent().find('input.file ').val("");
//input.fileUpload and input#uploadre both need to empty values for particular div
}
elm.remove();
}
}
});
</script>
What I want is to call Object.createObjectURL(this.files[0]) to get the object URL, and use that as the src of your img; (just don't even bother with the FileReader).
Something like this?
function readURL() {
var file = this.files[0]
var reader = new FileReader();
var base64string = getBase64(file);
reader.onload = function () {
reset($newinput.next('.delbtn'), true);
$newinput.attr('src', e.target.result).show();
$newinput.after('<div class="delbtn delete_upload" title="Remove"><span class="bbb-icon bbb-i-remove2"></span></div>');
var blob = dataURItoBlob(base64string);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
I'm not sure if this will work and due to the vagaries of Stack Snippets, can't demonstrate its viability here on Stack Overflow, but theoretically, you should be able to use URL.createObjectURL to create the appropriate URL for your image, without going through the whole base 64 rigmarole.
var $newinput = $(this).parent().parent().parent().find('.portimg ');
if (this.files && this.files[0]) {
$newinput.attr('src', URL.createObjectURL(this.files[0]));
// if the above doesn't work, you could try to create a new Blob
var fileBlob = new Blob(this.files[0], { type: "image/png" })
// Substitute "image/png" with whatever image type it is
$newinput.attr('src', URL.createObjectURL(fileBlob));
That should render the appropriate URL for the image's source.
Note that it is best practice to revoke the object URL when you are done with it. I'm not sure that's necessary in this case, since presumably you want to show the image until the page is closed. However, if the user can upload a new image, do something like:
if ($newinput.attr('src').indexOf('blob') > -1) {
URL.revokeObjectURL($newinput.attr('src'));
}
Add that before setting the new source and you shouldn't need to worry about memory leaks (from this use of createObjectURL anyway...).
For more information on Blob URLs, see this answer by a now-anonymous user to What is a blob URL and why it is used?
I need to read a file locally using javascript.
I know that for security reasons the possibility of doing this directly is inhibited.
Is there any way to work around this?
Furthermore, if I try to use the features of the File API specification, I can't get the "load" button to work if the button itself is not directly attached in the document.body. I would like this button to work even if attached to child type elements. Is there a solution for this?
Thank you very much
fileReader() {
console.log("FileReader Called");
var fileInput = document.getElementById('file');
var fileDisplayArea = document.getElementById('source-container');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!";
}
});
}
Hi i have these codes to read the file the user has uploaded:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#myImg').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
And the output is a whole chunk of data:
Is there any way i can get the path from the data? for example C:\Users\blackLeather\Desktop
If no,is there another way to get the image directory without having to add into another folder?
Is there any way i can get the path from the data?
No. None at all. That information is not provided to the JavaScript layer by the browser, for security reasons.
Add this in element:
onchange="loadFile(event)
var loadFile = function(event) {
var image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
This is my function:
FileCropped.prototype.change = function () {
var obj = $(this).data("plugin.file-cropped");
var files = obj.$element[0].files;
var file;
var URL = window.URL || window.webkitURL;
var blobURL;
if (files && files.length) {
file = files[0];
console.log("I have files");
if (/^image\/\w+$/.test(file.type)) {
blobURL = URL.createObjectURL(file);
obj.$element.val('');
obj.$hidden[0].value = blobURL;
//URL.revokeObjectURL(blobURL);
} else {
window.alert('Please choose an image file.');
}
} else
{
console.log("No files?");
}
}
I am trying right now to attach the blob to an existing form input but it does not work. With the chrome debugger I see the method works fine and follow the expected path, but at the time of submit the server gets nothing.
Any hint?
Edit: of course the function has no value right now. I could just use the normal file input. The goal is to be able to manipulate the blob before attaching it to the form.
You can use FileReader to read the file as data URL
var fileReader = new FileReader();
fileReader.addEventListener('load', function () {
blobURL = fileReader.result;
obj.$hidden[0].value = blobURL;
});
fileReader.readAsDataURL(file);
There is the following code which makes preview before uploading on the server:
$(function(){
var preview = $(".preview");
$("#menu_image").change(function(event){
var input = $(event.currentTarget);
var file = input[0].files[0];
var reader = new FileReader();
reader.onload = function(e){
var img = new Image;
img.onload = function() {
if ((img.with != 160) || (img.height != 160)) {
return;
}
preview.attr("src", img.src);
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
});
But this code doesn't check file's type. How can I do it? Thanks in advance.
You don't need to load the FileReader to know file type.
Using your code:
var file = input[0].files[0];
is as easy as checking the file.type property.
You can check if the file is an image:
if (file.type.match('image.*')) {
console.log("is an image");
}
And which type of image is:
if (file.type.match('image.*')) {
console.log("is an image");
console.log("Show type of image: ", file.type.split("/")[1]);
}
Note that file.type.split("/")[1] should be an "image"
You can do something similar to check the file extension:
var extension = file.name.substring(file.name.lastIndexOf('.'));
// Only process image files.
var validFileType = ".jpg , .png , .bmp";
if (validFileType.toLowerCase().indexOf(extension) < 0) {
alert("please select valid file type. The supported file types are .jpg , .png , .bmp");
return false;
}
Try using the extension selector like this:
if($('img[src $= "jpg"]')) // if extension is jpg then dosomething
dosomething;