the following errors appear in console:
aes.js Failed to load resource: the server responded with a status of 404 (Not Found)
script.js Failed to load resource: the server responded with a status of 404 (Not Found)
aes.js Failed to load resource: the server responded with a status of 404 (Not Found)
script.js Failed to load resource: the server responded with a status of 404(Not Found)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>JavaScript File Encryption App</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="Docrypt_function.js"></script>
</head>
<body>
<a class="back"></a>
<div id="stage">
<div id="step1">
<div class="content">
<h1>What do you want to do?</h1>
<a class="button encrypt green">Encrypt a file</a>
<a class="button decrypt magenta">/Decrypt a file</a>
</div>
</div>
<div id="step2">
<div class="content if-encrypt">
<h1>Choose which file to encrypt</h1>
<h2>An encrypted copy of the file will be generated. No data is sent to our server.</h2>
<a class="button browse blue">Browse</a>
<input type="file" id="encrypt-input" />
</div>
<div class="content if-decrypt">
<h1>Choose which file to decrypt</h1>
<h2>Only files encrypted by this tool are accepted.</h2>
<a class="button browse blue">Browse</a>
<input type="file" id="decrypt-input" />
</div>
</div>
<div id="step3">
<div class="content if-encrypt">
<h1>Enter a pass phrase</h1>
<h2>This phrase will be used as an encryption key. Write it down or remember it; you won't be able to restore the file without it. </h2>
<input type="password" />
<input type="button" value="encrypt the file!" id="button proccess red"/>
</div>
<div class="content if-decrypt">
<h1>Enter the pass phrase</h1>
<h2>Enter the pass phrase that was used to encrypt this file. It is not possible to decrypt it without it.</h2>
<input type="password" />
<input type="button" value="dencrypt the file!" id="button proccess green"/>
</div>
</div>
<div id="step4">
<div class="content">
<h1>Your file is ready!</h1>
<input type="button" value="download your file" id="download button"/>
</div>
</div>
</div>
</body>
<script src="assets/js/aes.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="assets/js/script.js"></script>
</html>
Javascript code:
/**
* Created by Steven on 07-Feb-17.
*/
(function(){
var body = $('body'),
stage = $('#stage'),
back = $('a.back');
/* Step 1 */
$('#step1 .encrypt').click(function(){
body.attr('class', 'encrypt');
// Go to step 2
step(2);
});
$('#step1 .decrypt').click(function(){
body.attr('class', 'decrypt');
step(2);
});
/* Step 2 */
$('#step2 .button').click(function(){
// Trigger the file browser dialog
$(this).parent().find('input').click();
});
// Set up events for the file inputs
var file = null;
$('#step2').on('change', '#encrypt-input', function(e){
// Has a file been selected?
if(e.target.files.length!=1){
alert('Please select a file to encrypt!');
return false;
}
file = e.target.files[0];
if(file.size > 1024*1024){
alert('Please choose files smaller than 1mb, otherwise you may crash your browser. \nThis is a known issue.');
return;
}
step(3);
});
$('#step2').on('change', '#decrypt-input', function(e){
if(e.target.files.length!=1){
alert('Please select a file to decrypt!');
return false;
}
file = e.target.files[0];
step(3);
});
/* Step 3 */
$('a.button.process').click(function(){
var input = $(this).parent().find('input[type=password]'),
a = $('#step4 a.download'),
password = input.val();
input.val('');
if(password.length<5){
alert('Please choose a longer password!');
return;
}
// The HTML5 FileReader object will allow us to read the
// contents of the selected file.
var reader = new FileReader();
if(body.hasClass('encrypt')){
// Encrypt the file!
reader.onload = function(e){
// Use the CryptoJS library and the AES cypher to encrypt the
// contents of the file, held in e.target.result, with the password
var encrypted = CryptoJS.AES.encrypt(e.target.result, password);
// The download attribute will cause the contents of the href
// attribute to be downloaded when clicked. The download attribute
// also holds the name of the file that is offered for download.
a.attr('href', 'data:application/octet-stream,' + encrypted);
a.attr('download', file.name + '.encrypted');
step(4);
};
// This will encode the contents of the file into a data-uri.
// It will trigger the onload handler above, with the result
reader.readAsDataURL(file);
}
else {
// Decrypt it!
reader.onload = function(e){
var decrypted = CryptoJS.AES.decrypt(e.target.result, password)
.toString(CryptoJS.enc.Latin1);
if(!/^data:/.test(decrypted)){
alert("Invalid pass phrase or file! Please try again.");
return false;
}
a.attr('href', decrypted);
a.attr('download', file.name.replace('.encrypted',''));
step(4);
};
reader.readAsText(file);
}
});
/* The back button */
back.click(function(){
// Reinitialize the hidden file inputs,
// so that they don't hold the selection
// from last time
$('#step2 input[type=file]').replaceWith(function(){
return $(this).clone();
});
step(1);
});
// Helper function that moves the viewport to the correct step div
function step(i){
if(i == 1){
back.fadeOut();
}
else{
back.fadeIn();
}
// Move the #stage div. Changing the top property will trigger
// a css transition on the element. i-1 because we want the
// steps to start from 1:
stage.css('top',(-(i-1)*100)+'%');
}
/* //the encryption button
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('button proccess red').addEventListener('click',function (e) {
} )
})
//the decryption button
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('button proccess green').addEventListener('click',function (e) {
} )
})
//the download button
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('download button').addEventListener('click',function (e) {
} )
})
*/
});
You need to execute the code when the window loads: $(function() { instead of just (function() {
Related
I found this code which, you select a pdf file in an input, and it returns the number of pages it has. It turns out that with this way of reading pdfs is the only one I have found that reads absolutely all pdfs correctly.
What I am trying to do is to isolate the code that reads the pdf file, so that I can pass it the path to the file instead of using the input. It is to then read all the files in a folder and display the total number of pages.
But I can't figure out where exactly I would have to pass the path to the pdf file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDF.js Example to Count Number of Pages inside PDF Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="text-center">Count Pages inside PDF Document</h1>
<div class="form-group container">
<input type="file" accept=".pdf" required id="files" class="form-control">
</div>
<br><br>
<h1 class="text-primary container" id="result"></h1>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.12.313/pdf.min.js"></script>
<script>
let inputElement = document.getElementById('files')
inputElement.onchange = function(event) {
var file = event.target.files[0];
//Step 2: Read the file using file reader
var fileReader = new FileReader();
fileReader.onload = function() {
//Step 4:turn array buffer into typed array
var typedarray = new Uint8Array(this.result);
//Step 5:pdfjs should be able to read this
const loadingTask = pdfjsLib.getDocument(typedarray);
loadingTask.promise.then(pdf => {
document.getElementById('result').innerHTML = "The number of Pages inside pdf document is " + pdf.numPages
// The document is loaded here...
});
};
//Step 3:Read the file as ArrayBuffer
fileReader.readAsArrayBuffer(file);
}
</script>
</html>
You need 2 modifications to make it work. Add "multiple" attribute to the input to allow the user to select multiple pdf files.
<input type="file" multiple accept=".pdf" required id="files" class="form-control">
And then loop through the array of files to calculated the number of pages in each:
[].forEach.call(event.target.files, file => {
Update:
Two additional changes have been added.
1. We must reset the file input at the end of the loop. Otherwise it will only work once and then stop.
// clear file selector to allow reuse
event.target.value = "";
2. We also must set the value "workerSrc" to prevent a console warning message. More details about that here.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.worker.min.js';
Run the code snippet to see how it works (hold shift key down to select multiple pdf files):
let inputElement = document.getElementById('files')
inputElement.onchange = function(event) {
[].forEach.call(event.target.files, file => {
//var file = event.target.files[i];
//Step 2: Read the file using file reader
var fileReader = new FileReader();
fileReader.onload = function() {
//Step 4:turn array buffer into typed array
var typedarray = new Uint8Array(this.result);
//Step 5:pdfjs should be able to read this
const loadingTask = pdfjsLib.getDocument(typedarray);
loadingTask.promise.then(pdf => {
document.getElementById('result').innerHTML += "<li>" + file.name + " has " + pdf.numPages + "pages</li>";
// The document is loaded here...
});
};
//Step 3:Read the file as ArrayBuffer
fileReader.readAsArrayBuffer(file);
})
// clear file selector to allow reuse
event.target.value = "";
}
// Must set worker to avoid error: Deprecated API usage: No "GlobalWorkerOptions.workerSrc" specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.worker.min.js';
<div class="container">
<h4 class="text-center">Count Pages inside PDF Document</h4>
<div class="form-group container">
<input type="file" multiple accept=".pdf" required id="files" class="form-control">
</div>
<br><br>
<ol class="text-primary container" id="result"></ol>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.min.js" integrity="sha512-g4FwCPWM/fZB1Eie86ZwKjOP+yBIxSBM/b2gQAiSVqCgkyvZ0XxYPDEcN2qqaKKEvK6a05+IPL1raO96RrhYDQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
You can't.
Browsers don't let you access local paths on a user's computer for security reasons.
The browser doesn't get to know that the pdf is at /home/USERNAME/confidentialdocs/file.pdf, it just gets a data blob with a given filename.
I have two files to make a CAPTCHA page, here's the HTML file
<!DOCTYPE HTML>
<html>
<head>
<title> Example </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<link rel="shortcut icon" href="#">
</head>
<body onload="example()">
<h1> Captcha Example </h1>
<div id="x"></div>
<label> Enter the text from Captcha above </label>
<input type="text" id="CaptchaInput">
<br> <br>
<input type="button" value="Enter" id="Button">
<script>
var Captcha ='{{ newData.CaptchaValue }}';
Button.addEventListener("click", function() {
if(Input === Captcha) {
console.log("Match");
} else {
console.log("Incorrect");
}
})
function example () {
$.ajax({
url: "/",
context: document.body
})
var img1 = new Image();
img1.src = "../np4A8.png";
}
</script>
</body>
</html>
And my Python file
import random
from flask import Flask, render_template
from captcha.image import ImageCaptcha
app = Flask(__name__)
result_str = ''.join(
(random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') for i in range(5)))
#app.route('/')
def generateCaptcha():
# Create an image instance of the given size
image = ImageCaptcha(width=280, height=90)
# Image captcha text will equal random result
captcha_text = result_str
# generate the image of the given text
data = image.generate(captcha_text)
# write the image on the given file and save it
image.write(captcha_text, result_str + '.png')
newData = {'CaptchaValue': result_str}
return render_template('main.html', newData=newData)
if __name__ == "__main__":
app.run(debug=True)
I always get the error:
Failed to load resource: the server responded with a status of 404 (NOT FOUND) np4A8.png:1
I need to change it to the captcha file name but first I wanted to work with an image that already exists. Basically I have the main directory and a templates folder with my HTML page. The main directory folder has the PNG images. I thought "../np4A8.png" was the previous directory and looking for a photo called np4A8.png. Please help me. I'm so close to finishing and been struggling with this
I am creating an online HTML form that gives people the option to upload a file. I am using google sheets to collect the data so I am using their google scripts feature. When I run my code everything works, meaning I get data inserted into cells, but not the file upload. Here is my Google Scripts code for the file upload:
function doGet(request) {
return HtmlService.createTemplateFromFile('Index')
.evaluate();
}
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function uploadFiles(data){
var folder = DriveApp.getFolderById('1pp1ELzGa2fZqU4IHAasZMHsmYx19pnYv');
var createFile = folder.createFile(data.image);
return createFile.getUrl();
}
From what I can tell the problem is at the data.image. This is where I am trying to retrieve my image so I can upload it into the folder. It must be that uploadFiles(data) is not properly bringing in data.
Here is the HTML and JavaScript:
<form id="myForm" onsubmit="handleFormSubmit(this)">
<h1 class="h4 mb-4 text-center" style="text-align:center"> <center>File Upload Testing</center></h1>
<table>
<tr>
<td colspan="11"><input type="file" id="image"></td>
</tr>
<input type="hidden" id="fileURL" name="fileURL">
</table>
<button type="submit" class="button button1" id="submitBtn">Submit</button>
</form>
<script>
document.getElementById('submitBtn').addEventListener('click',
function(e){
google.script.run.withSuccessHandler(onSuccess).uploadFiles(this.parentNode);;}
)
function onSuccess(data){
document.getElementById("fileURL").value = data;
}
</script>
I have a feeling that the e parameter is not retrieving the data above, however I don't really understand how it works. It could also be this.parentNode that's not grabbing the fike.
I am using the onSuccess function to retrieve the link so I can put it into my google sheet for quick access.
This is the error I receive;
Here is a link to the google sheet. To reach google scripts go to 'Tools -> Script Editor'.
https://docs.google.com/spreadsheets/d/16w8uB4OZHCeD7cvlrUv5GHP72CWxQhO1AAkF9MMSpoE/edit?usp=sharing
Here is another technique I attempted to use:
Javascript:
function uploadthis(fileForm){
const file = fileForm.image.files[0];
const fr = new FileReader();
fr.onload = function(e) {
const obj = {
// filename: file.name
mimeType: file.type,
bytes: [...new Int8Array(e.target.result)]
};
google.script.run.withSuccessHandler((e) => console.log(e)).uploadFiles(obj);
};
fr.readAsArrayBuffer(file);
}
Google Script:
function uploadFiles(data){
var file = Utilities.newBlob(data.bytes, data.mimeType); // Modified
var folder = DriveApp.getFolderById('1pp1ELzGa2fZqU4IHAasZMHsmYx19pnYv');
var createFile = folder.createFile(file);
return createFile.getId(); // Added
}
Thank you!
I have to create a html list with one li name import . On back i have create input type ="file" which will be hidden .
If user click on import it should fire file upload from back using .click()[![enter image description here][1]][1].
Once the use select the .json file it can be of any name ..
Then On click of open button of file upload it should save the json and pass the json object with an event dispatcher . I have create event dispatcher but not able to get json
Issue : I am not able to save the json object using .onChange and also .onChange work single time then i have to refresh then it work again.
Requirement: On click of import button, hidden file import will fire then on selecting the json file of any name (json filem can be of any name) function will save the json object and json object will be sent using iframe using event dispatcher .
Issue:: Not able to save the json or get the json . I tried getjson but it if for single file name .
<!DOCTYPE html>
<html>
<meta charset="UTF-8"/>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function (){
$('#import').click();
});
$('#import').on('change',function () {
// not able to get json in a json object on selection of json file
var getJson = $('#import')[0].files;
// dispatcher just take json object and it will send to iframe .
// WindowDispatcher("Send Json", getJson);
});
});
</script>
</head>
<body>
<input type='file' id='import' style = "display:none" accept='.json ' aria-hidden="true" >
<ul>
<li>
<button id="importLink" >import</button>
</li>
</ul>
</body>
</html>
$(document).ready(function(){
$("#importLink").click(function(){
$("#import").click();
});
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
$("#import").on('change',function(e){
var file = e. target. files[0];
var path = (window.URL || window.webkitURL).createObjectURL(file);
readTextFile(path, function(text){
var data = JSON.parse(text);
console.log(data);
//Your ajax call here.
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="file" id="import" style="display:none" accept='.json' aria-hidden="true" >
<ul>
<li id="importLink">import</li>
</ul>
<output id="list"></output>
<div id="name">list</div>
<div id="age">list</div>
Read file from e. target. files[0];
Off what I can see, you are missing an argument list for your import onChange listener.
In the first image, you are calling $'#import').click() -- you are missing the leading (
you should be getting a javascript error when running the code you mentioned, since you don't include at least an empty argument list when the file input changes, though I could be wrong.
I've tried use javascript to open text file and get his name and his content, so right now I'm stuck at string, because I used input - type file to get directory / path.
Anyway, my question what is wrong in the next code, and how can i get text file content using javascript?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Display Text Files</title>
<script type="text/javascript">
var str = document.getElementById('txt').value;
function display() {
if (str != "") {
var filename = str.split("/").pop();
document.getElementById('filename').innerHTML = filename;
}
}
</script>
</head>
<body>
<form method="get" action="#" >
<input type="file" accept="text/plain" id="txt" />
<input type="submit" value="Display Text File" onclick="display();" />
</form>
</body>
</html>
EDIT: I also wanna disable in input file the all files opition (*) to text files only (.txt).
Thanks!
Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.
Here is some code I wrote only this morning to do just this. In my case I simply drag a file onto the HTML element which is here referenced as panel.in1 but you can also use <input type="file" /> (see the reference below).
if (window.FileReader) {
function dragEvent (ev) {
ev.stopPropagation ();
ev.preventDefault ();
if (ev.type == 'drop') {
var reader = new FileReader ();
reader.onloadend = function (ev) { panel.in1.value += this.result; };
reader.readAsText (ev.dataTransfer.files[0]);
}
}
panel.in1.addEventListener ('dragenter', dragEvent, false);
panel.in1.addEventListener ('dragover', dragEvent, false);
panel.in1.addEventListener ('drop', dragEvent, false);
}
It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.
I got most of the mechanism on how to do this from MDN : https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications