What does all my images start with the same sequence? - javascript

Continuing my experiments and my last question (Solved BTW, THANKS!!) i realized that all the images that i upload start with the same sequence:
/9j/4AAQSkZJRgABAQAAAQABAAD/
Does anyone knows what is that? my first impression was that it should be somekind of CRC but it has to change with every upladed file
My code is:
<button type="button" class="btn btn-primary" id="bid_uploadPicture">Subir Imagen</button>
<input type="file" id="file" accept='image/*' style="display:none;" />
jQuery(function ($) {
$("#bid_uploadPicture").click(function () {
event.preventDefault();
document.getElementById("file").click();
});
$("#file").change(function () {
var fr = new FileReader();
fr.onload = function (e) {
data = new Uint8Array(e.target.result)
console.log(e.target.result);
}
//fr.readAsArrayBuffer(this.files[0]);
fr.readAsDataURL(this.files[0]);
});
});

I just give with the answer, im posting here in case some one else has the same interest
It turns out that this sequence is the JPG signature and the format structure of the uploaded picture as explained in this wikipedia article:
https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format
Regards!!!

Related

HTML getting an image from a file upload

I am working through an old project and trying to fix a few bugs.
I have a file upload in HTML
function updateImage() {
circleArray = [];
newPic = `id="taco" width="300" height="300" src="${$(
"#myFile"
).val()}" alt="prime.png"`;
$("#hide").empty();
$("#hide").append(`<img ${newPic}>`);
makeCanvas();
}
<form>
<input type="file" id="myFile" name="filename">
<button id='submit'>Submit</button>
</form>
When I click the submit button I have a function that should update the image displayed with the newly uploaded image.
It seems like the file is uploaded but I am accessing it incorrectly.
I see the following error
GET c:\fakepath\IMG_0544.jpg net::ERR_UNKNOWN_URL_SCHEME
Consider the following.
$(function() {
function updateImage() {
var newPic = $("<img>", {
id: "taco",
alt: "prime.png"
}).css({
width: 300,
height: 300
});
var myFile = $("#myFile")[0].files[0];
var reader = new FileReader();
reader.onload = function(event) {
newPic.attr("src", event.target.result);
$("#hide").empty().append(newPic);
};
reader.readAsDataURL(myFile);
//makeCanvas();
}
$("form").submit(function(event) {
event.preventDefault();
updateImage();
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="file" id="myFile" name="filename">
<button id='submit'>Submit</button>
</form>
<div id="hide"></div>
This reads the file from the input element and renders it as an Image.
I'm unable to reproduce the problem in your dynamic "code snippet", but it's pretty clear what's happening.
The error GET c:\fakepath\IMG_0544.jpg net::ERR_UNKNOWN_URL_SCHEME means that your browser was trying to access a file on your C:\ drive as though it were a remote URL. You can't do that :)
ONE POSSIBLE SOLUTION: try uploading the image and rendering it as an "embeddd image", per this article:
https://www.thesitewizard.com/html-tutorial/embed-images-with-data-urls.shtml
ANOTHER POSSIBLE SOLUTION: Use FileReader.readAsDataURL():
https://www.tutorialrepublic.com/faq/how-to-preview-an-image-before-it-is-uploaded-using-jquery.php
Try this :
function updateImage() {
circleArray = [];
newPic = `id="taco" width="300" height="300" src="${$("#myFile").get(0).files[0].name}" alt="prime.png"`;
$("#hide").empty();
$("#hide").append(`<img ${newPic}>`);
makeCanvas();
}

javascript file reader on button click error: undefined refference

I'm trying to get a local file from a system, I did some searching and came around a way of doing this, when I tried to implement it in my code, I got the error:
Uncaught TypeError: Cannot read property 'type' of undefined
document.getElementById('add-new-cat').addEventListener('click', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files;
if(files.type.match('image.*')) {
var reader = new FileReader();
reader.onload = (function(theFile) {
})(files);
var catIMG = reader.readAsBinaryString(files);
alert(catIMG);
}
}
<input type="file" name="cat_path_orig" id="cat-path-orig">
<button class="btn btn-primary" id="add-new-cat">add</button>
I wouldn't know how to trigger the function with the file included, because I know it's looking for a value in the button that's being clicked
The click event object doesn't have a files property. I think you're looking for the files property on the input type="file" object:
document.getElementById('add-new-cat').addEventListener('click', handleFileSelect, false);
function handleFileSelect(evt) {
var files = document.getElementById("cat-path-orig").files; // ****
console.log("files.length: " + files.length);
Array.prototype.forEach.call(files, function(file) {
console.log(file.name + ": " + file.type);
});
}
<input type="file" name="cat_path_orig" id="cat-path-orig">
<button class="btn btn-primary" id="add-new-cat">add</button>
A couple of other notes:
You'll want to look at the type property on each individual file (see the snippet above). In your example, there will be only one (because there's no multiple attribute on the input type="file"), so you could just use files[0] rather than the loop I've used above.
Your use of readAsBinaryString is also incorrect; here's an answer with a correct example.

Generating File object that can be read by javascript FileReader without HTML Input tag

I'm a newbie to dynamic HTML websites so bear with me. This is a locally run webpage for my network only. On load of my webpage, I want it to read a text file and place the data into a textarea. This will then update every couple seconds to display the changes in the text file. I've read several examples on how to do it using the input tag in HTML, but I want it to load without user input.
I'd like to use FileReader() with javascript, but don't know how to make an object that can be read by readAsText(object_here).
<script>
var intervalID1;
function updateTextTimer()
{
intervalID1 = setInterval(updateText,5000);
}
function updateText()
{
var temp = document.getElementById('logOutput');
var reader = new FileReader();
var fileName = "test.txt";
reader.onload = function(e) {temp.value = e.target.result;}
reader.readAsText(file_object);
}
</script>
Again, I'd prefer to use FileReader because it would be easy, but willing to take suggestions. Thanks!
Try using .load()
var timeout = null;
(function loadText() {
$("#logOutput").load("test.txt", function() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(loadText, 5000)
})
}())
e.g.,
var timeout = null, obj = null;
(function loadText() {
obj = URL.createObjectURL(new Blob([$("#input").val()], {
type: "text/plain"
}))
$("#logOutput").load(obj, function() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(loadText, 5000)
})
}())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<label for="input">input text here:</label><br />
<textarea id="input">
</textarea>
<br />
<label for="logOutput">output:</label>
<br />
<textarea id="logOutput" disabled>
</textarea>
readAsText Only accept Blob object, you can ref how to create a Blob OBj.

Display local android image in a webview using javascript or jquery

Scene: I am trying to display a file image selected from the gallery into a webview using javascricpt and/or jquery but I am not able to do so. The same works while opening the html in a desktop browser.
What I have tried so far is this in the android code is this:
Written the openFileChooser code and getting the image path and also the image bytes.
calling the following in onActivityResult method:
String js = "javascript:loadImage(file://" + imagePath + ")";
mWebView.loadUrl(js);
The html looks like this:
<div class="file_chooser">
<!-- <input type="submit" value="File chooser" id="btnSubmit" onclick="sayHello();" > -->
<input type="file" name="banner_image" id="banner_image" onChange="loadImage(this);" accept="image/*" />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<img alt="" id="image" src="" width="200px" height="200px" onclick="showSrc(this.src);">
</div>
and the javascript looks like this:
<script type="text/javascript">
function loadImage(input) {
if (input.files && input.files[0]) {
Android.alert('input: ' + input.files[0]);
var reader = new FileReader();
reader.onload = (function(input) {
return function(e) {
$('#image').attr('src', e.target.result);
console.log('onload stage finished');
};
})(input);
reader.onloadend = (function() {
// $('#image').src(file.name);
});
reader.readAsDataURL(input.files[0]);
//data:image/jpg;base64,xxxxxxxxxxxxxxxxxxxxxxxxxxxx -> this did not work
}
function showSrc(src) {
Android.alert('src : ' + src);
}
</script>
But i seem to be messing with the android code and also javascript, since i do not know jscript that well.
Please assist as to how to display an image after selection from the gallery.
EDIT:
I have gone through lotsa links that show how to call a javscript function from android , and how to display an image by calling loadBaseUrl with the new html code that has an image inside the src tag, like this, but this is not what I really want.
For those who fall into such a case:
I changed how the loadImage method functions to one that converts a file received into bytes
Steps:
1. Read a file from android and send the path over to the js function
2. Pass the path to a reader and when the reader loads the file, the onLoadEnd method gets called
3. Convert the file to bytes using the code
var stringToReplace = reader.result;
stringToReplace = stringToReplace.replace('data:base64,','data:image\/jpeg;base64,');
Set the image source to the string obtained in #3.

Passing path to uploaded file from HTML5 drag & drop to input field

I'm working on an application (in Node.js, which is irrelevant for this case) which allows the user to upload an image. It works fine using a form with an input (type="file") field.
However, what I want is to be able to upload an image using HTML5 drag and drop instead. As far as i've come it's possible to drag an image to the client, and the image thumbnail is displayed in a div. However I really need some help with getting the file upload working.
The thing is that I want to use the form that i'm using right now, and (somehow) pass the file's path to the input field, i.e. the flow will work exactly as it do now, but instead of choosing a file by browsing it I want to attach it to the input field by drag and drop.
In the js code below for drag and drop the file that was dragged to the client is stored in the variable "file", and i'm able to use "file.name", "file.type" and "file.size" exactly the same way as it works since before with the form. However, I can't access the files "path" (file.path) which makes it impossible to access the file server side for uploading the same way as I do it since before.
The question is, is it possible to pass the file object to the input field after the file has been dragged to the client, so that I can click on "submit" and upload the file? If so, how could this be done?
Thanks in advance!
the dropbox as well as the form i'm using for file uploads:
<div id='upload'>
<article>
<div id='holder'>
<p id='status'>File API and FileReader API not supported</p>
</div>
</article>
<form method='post' enctype='multipart/form-data' action='/file-upload'>
<p>
<input type='file' name='thumbnail'>
</p>
<p>
<input type='submit'>
</p>
</form>
</div>
the code for drag and drop:
uploadImage: function(){
var holder = document.getElementById('holder'),
state = document.getElementById('status');
if (typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = 'File API & FileReader available';
}
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
holder.style.background = 'url(' + event.target.result + ') no-repeat center';
};
reader.readAsDataURL(file);
return false;
};
},
You cannot use the file input to add the file data.
Nevertheless, what you can do (among other technics) is to use the base64 (natively available through the reader.onload event as event.target.result, when using readAsDataURL method) encoded data and put it into an hidden field :
html
<article>
<div id='holder'>
<p id='status'>File API and FileReader API not supported</p>
</div>
</article>
<form method='post' enctype='multipart/form-data' action='/file-upload'>
<input type='file' name='thumbnail' />
<input type='hidden' name='base64data' />
<input type='submit' formenctype='application/x-www-form-urlencoded' />
</form>
js
reader = new FileReader();
reader.onload = function (event) {
document.getElementById('base64data').setAttribute('value', event.target.result);
};
reader.readAsDataURL(file);
From the server side you'll be able to get the base64 encoded data from the file, just decode it and use it as you want.
While submitting the form, you could also change the "enctype" attribute (done through the formenctype attribute) and remove the basic html file input, since the data will be post in a text field.
It is impossible to know the path of the field for security purposes. With drag and drop you must have it upload independently of the main form. Look here for an example: http://www.sitepoint.com/html5-file-drag-and-drop/
I find that the hidden field set in reader.onload (see answer by #challet) is not set when acccessed in code behind. I am using asp.net and a WebForms project. To access the hidden fields I have to prepend MainContent_ to the field names. aspx code is below
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
...
<script type="text/javascript">
function dropHandler(ev) {
alert("File(s) dropped");
// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();
//alert("Default prevented");
if (ev.dataTransfer.items) {
if (ev.dataTransfer.items.length > 1) {
alert("Only single files can be dragged and dropped into Caption Pro Web");
return;
}
// If dropped items aren't files, reject them
if (ev.dataTransfer.items[0].kind === 'file') {
var file = ev.dataTransfer.items[0].getAsFile();
document.getElementById("MainContent_DroppedFileName").value = ev.dataTransfer.items[0].name
reader = new FileReader();
reader.onload = function (event) {
document.getElementById('MainContent_DroppedFileContent').value = event.target.result;
};
reader.readAsDataURL(ev.dataTransfer.items[0]);
}
} else {
// Use DataTransfer interface to access the file(s)
if (ev.dataTransfer.files.length > 1) {
alert("Only single files can be dragged and dropped into Caption Pro Web");
return;
}
document.getElementById("MainContent_DroppedFileName").value = ev.dataTransfer.files[0].name
document.getElementById("MainContent_DroppedFileContent").value = "Test";
reader = new FileReader();
reader.onload = function (event) {
document.getElementById("MainContent_DroppedFileContent").value = event.target.result;
};
reader.readAsDataURL(ev.dataTransfer.files[0]);
}
document.getElementById('<%=btnDrop.ClientID %>').click();
}
</script>
...
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
<p>Drag image to this Drop Zone ...</p>
</div>
<asp:HiddenField ID="DroppedFileName" runat="server" />
<asp:HiddenField ID="DroppedFileContent" runat="server" />
...
</asp:Content>
I access the hidden fields from c# as shown below
protected void btnDrop_Click(object sender, EventArgs e)
{
string FileName = DroppedFileName.Value;
string FileContent = DroppedFileContent.Value;
}
If I use Internet Explorer as the target browser (not running VS as Admin as this disables drag/drop!) and set a breakpoint in the reader.onload() function the hidden field DroppedFileContent contains the encoded file content, but when I try to access it from btnDrop_Click it only contains "Test" as set before reader.onload() and does not contain the encoded file content. The field DroppedFileNam.Value is as set in the Javascript.

Categories

Resources