File Validation in Javascript - javascript

We are working on a Email Encrypted Service. Here I have designed a html page (User Registration) where I have provided an area for uploading a file with extentions .crt, .cer and .der
This is HTML Content:
<section>
<label class="label">PubLic Key File</label>
<div>
<input type="file" id="fileInput">
</div>
<div id="fileDisplayArea"></div>
</section>
<button type="submit" class="button">Submit</button>
Javascript Code is:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!";
}
});
}
I have copied this Javascript Code (beginner in javascript) . It Only Accepts image file. I want to change this code which only accepts .crt, .cer and .der Extentions.
Thank you :)

Your current regex will actually match any filename that contains the word "image" (any part of the filename that is "image" followed by zero or more characters)
If you want to match filenames that end in ".crt", ".cer" or ".der", you can use this regex:
var imageType = /\.crt|cer|der$/
You can test regular expressions using Rubular

Related

Show local image file on the web

I'm developing a website to recommend clothes. So, I want customers to put their image which is in their local.
First, I tried <input type='file' accept='image/*' ~~>. But it doesn't provide customizing option. I must show the button with my picture.
Therefore I tried button option and write the code like this.
function openImageFile() {
var input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.click();
input.onchange = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var dataurl = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
output.width = 125;
output.height = 125;
};
photo = input.files[0];
reader.readAsDataURL(input.files[0]);
}
}
<button type="button" id="test" onclick="openImageFile()"><img src="blah.png"></button>
<img id='output'>`
Convert your image to data protocol.
Converter: https://base64.guru/converter/encode/image
Set the src of your image element to:
<image src="data:image/png;base64,OUPUT_FROM_ENCODER" />
This allows your website to load a image without it being hosted by a URL

Save <img> to File Share using AJAX

I am trying to somehow save my image generated with <input type="file" id="file_capture" capture="user" accept="image/*"/> through vb.net ajax and save the file into a file share folder.
I need image capture so that if the user is on their phone it will screen capture.
I have tried jquery-webcame with no luck and have ended with only HTML Capture working up to the point when I need to save the file.
So far the image src looks something like this data:image/jpeg;base64,/...
When I pass the src into ajax I tried to read it using Net.WebClient but I am unsure how to get the address of the img when all I have is the src value to use for My.Computer.Network.DownloadFile
VB.NET
<System.Web.Services.WebMethod(EnableSession:=True)> Public Shared Function SaveImage(ByVal src As String) As String
Try
Dim client As Net.WebClient = New Net.WebClient
Dim destination = "\\serverName\FolderShareName\"
client.DownloadFile(src, destination)
Catch ex As Exception
End Try
Return "Pass"
End Function
HTML
<label class="cameraButton" style="min-width:150px;">Capture File
<input type="file" id="file_capture" capture="user" accept="image/*"/>
</label>
<div id="imageHolder" class="col-sm-12" style="border:1px solid red;text-align:center;min-width:150px;" runat="server">
</div>
JAVASCIRPT [I created it this way so multiple images can be uploaded]
$('#file_capture').change(function () {
AddNewImage(this);
});
function AddNewImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var id = $("#imageHolder > div > img").length
var fullid = "uploadImage" + id++;
var DIV = document.createElement("DIV");
DIV.className = "imgWrap"
DIV.ID = "imgWrapID" + id++;
DIV.style.display = "inline-block";
DIV.style.padding = "10px";
document.getElementById('imageHolder').appendChild(DIV);
var img = new Image(200, 200);
reader.onload = function (e) {
img.src = e.target.result;
img.id = fullid
}
reader.readAsDataURL(input.files[0]);
var btn = document.createElement("BUTTON");
btn.innerHTML = "x";
btn.className = 'top-right';
btn.name = DIV.ID
btn.title = fullid
btn.onclick = function () {
$("#" + this.name).remove();
$("#" + this.title).remove();
$(this).remove();
return false;
};
DIV.appendChild(btn);
DIV.appendChild(img);
}
}
client.DownloadFile(src, destination)
clearly won't accept the 64bit src value of the image so I need to somehow convert it to a address.

Find Date in Text and save this Date in variable

I have a txt file which get read with javascript.
function handleTextFile(evt)
{
var files = evt.target.files;
var reader = new FileReader();
reader.onload = function(){
Text = reader.result.toLowerCase();
};
reader.readAsText(files[0]);
}
I want find in var >Text< all Dates.
The located date shall be saved in a variable. The only thing i know-> i can match date formats with code
var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
but i want not only a true or false output. I want the Value of this located date.
Anyone has a link or a some code for me?
Here is a working snipped with regex for dates in format 00-00-0000.
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
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) {
var myRegexp = /\b(\d{2}-\d{2}-\d{4})/g;
var match = myRegexp.exec(reader.result);
fileDisplayArea.innerText = match;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
<div id="page-wrapper">
<h1>Your date reader.</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
I used this tutorial to assemble snipped above .

How to send json format after make base64 encoded image

Here i am converting two images for base64 ,this one working fine after that i want make one json format, so i am trying like this but i no able to get answer. i am getting error like "message": "Uncaught ReferenceError: floor_image is not defined", how to solve this issue and send json format
$(document).ready(function(){
$('#submit').click(function(){
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var floor_image = fileLoadedEvent.target.result; // <--- data: base64
console.log("Converted Base64 version 1 " + floor_image); // i am getting answer here
}
fileReader.readAsDataURL(fileToLoad);
}
var filesSelected = document.getElementById("inputFileToLoad1").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var property_image = fileLoadedEvent.target.result; // <--- data: base64
//console.log("Converted Base64 version 2 " + property_image); // i am getting answer here
}
fileReader.readAsDataURL(fileToLoad);
}
var json = {
"FloorImage" :floor_image,
"PropertyImage" : property_image
}
console.log(json);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form id="idname">
<input id="inputFileToLoad" type="file" /><br><br>
<input id="inputFileToLoad1" type="file" />
<br><br><br><br>
<input type="button" value="Submit" id="submit">
</form>
You do not have the floor_image in the global scope. Try to write var floor_image; outside of the method, then set floor_image to your result as you do, but remove the var keyword in the method. The same goes for property_image and json
Like this:
$(document).ready(function(){
var json={FloorImage:"not loaded yet",PropertyImage:"not loaded yet"};
var floor_image;
var property_image;
$('#submit').click(function(){
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
floor_image = fileLoadedEvent.target.result;
json.FloorImage=floor_image;
}
fileReader.readAsDataURL(fileToLoad);
}
var filesSelected = document.getElementById("inputFileToLoad1").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
property_image = fileLoadedEvent.target.result;
json.PropertyImage=property_image;
}
fileReader.readAsDataURL(fileToLoad);
}
console.log(json); // you are logging the json before the images are loaded, because this code is executed before the code inside onLoad.
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="idname">
<input id="inputFileToLoad" type="file" /><br><br>
<input id="inputFileToLoad1" type="file" />
<br><br><br><br>
<input type="button" value="Submit" id="submit">
</form>
Scenario
Try to load the FloorImage first, you will see the text: "not loaded yet" in both properties of the json-object. Then try to load the PropertyImage, and you will se the base64 of the FloorImage inside your json-object, but the text "not loaded yet" on the PropertyImage. This is because the images are not finished loading when you print the json-object. However the images are there after the onload-method is done.
There are 2 problems:
floor_image and property_image are in local scope. You should
move them to click function's scope
onload is just a callback. It means that json object may
be created before files have loaded. You should only create it after
2 onload functions called (for example, use flag to determine
onload called or not, and only create json when both of them are
true)

Javascript Image Preview for page with lots of forms

I have a bunch of forms on a page that allow a user to edit information for each respective form. One of the inputs for the form is an image upload.
The forms are of the form below:
<form class="myForm" ...>
<div class="imagePreview"></div>
<input type="file" name="myImage" onchange="handleFiles(this.files)" />
</form>
And I have javascript to handle the image preview as follows:
function handleFiles(files) {
$(".obj").remove();
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var pic_div = document.getElementById("imagePreview");
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
pic_div.appendChild(img);
var reader = new FileReader();
reader.onload = (
function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
}
)(img);
reader.readAsDataURL(file);
}
}
I want to replace the line:
var pic_div = document.getElementById("imagePreview");
with the appropriate line. This is where I am getting confused. I don't know how to refer to the div of class "imagePreview" for THIS FORM of class myForm.
Any help is much appreciated.
The problem is that you're getting the div with the Id imagePreview, when the div in the form have the imagePreview CSS class, what you can do is either give the div the required id, more less like this:
<div id="imagePreview"></div>
Or, if you will have multiple divs with the same class get them using jQuery like this:
$(".imagePreview").each(function(index){
//Do Something
});
Or:
var pic_div = $(".imagePreview")[0]

Categories

Resources