Display multiple pdf on single web page - javascript

I am building a web page in which I used pdf.js project of Mozilla and its working perfectly.
But I have a need to show multiple pdf on single page, which are to be placed in different divisions.
Someone supposed me to use iframes but I need to show them in div only or i can use buttons by which i can switch to other pdfs on same page
The way of switching to other pdf with button is perfect solution and it can be done by AJAX but I don't know how to implement this functionality with AJAX. Does any one can provide me way to implement it ?
Mozilla developers have implemented following code to change the pdf in viewer when user select a pdf file from choose file tool box:
window.addEventListener('change', function webViewerChange(evt) {
var files = evt.target.files;
if (!files || files.length == 0)
return;
// Read the local file into a Uint8Array.
var fileReader = new FileReader();
fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
var data = evt.target.result;
var buffer = new ArrayBuffer(data.length);
var uint8Array = new Uint8Array(buffer);
for (var i = 0; i < data.length; i++)
uint8Array[i] = data.charCodeAt(i);
PDFView.load(uint8Array);
};
But i want to work this code on the button click event and it should load the pre-specified pfd on viewer.

Related

Uploading Multiple Files with XMLHttpRequest Uploads First File with Different Names

I am working on a page that has the ability to load multiple pdf files on a location for use later in another page.
I am using JavaScript's XmlHttpRequest to enable me to send the necessary files to the location. When I was testing the functionality, I noticed something weird was happening: while the same number of files are uploaded with the correct names, when I open them up they are all the first file I selected to upload.
I am baffled as to why this happens and was wondering if you could help me understand what is going on. That would be greatly appreciated.
function runRule(){
if(!workOrdersUploadCtrlr.files){
alert("No files have been selected!");
return;
}
var thefile = workOrdersUploadCtrlr.files;
var uploader = new XMLHttpRequest();
var file = new FormData();
for(var i=0; i < thefile.length; i++) {
if(workOrdersUploadCtrlr.cancelledFiles.indexOf(i) < 0){
file.append('file',thefile[i]);
uploader.onreadystatechange = function(){
if(uploader.readyState === 4 && uploader.status === 200){
console.log(uploader.responseText);
}
}
uploader.open('POST',"/url",true);
uploader.send(file);
}
}
}

Upload and read file client side, with angular 2

I need log file(s) from user so I can read and analyze those. For example somekind of drop area, where user drops a file, then I can read it with javascript?
I use Angular2 rc5. I have node.js running backside, but I don't need the data there. I need it only at client side.
Is it possible to read and parse file content with just frontend tech, like angular2 and javascript? Or do I have to upload the file to server and analyze it there?
It is possible!
I ended up doing it like this. This reads all the files that are selected with file dialog. I don't need to send these to node.js. I can just manipulate these on client.
<input type='file' accept='text/plain' multiple (change)='openFile($event)'>
openFile(event) {
let input = event.target;
for (var index = 0; index < input.files.length; index++) {
let reader = new FileReader();
reader.onload = () => {
// this 'text' is the content of the file
var text = reader.result;
}
reader.readAsText(input.files[index]);
};
}
It is very basic example of how you can do it.

Javascript - Download prompting of self created batch files

I"m a noob in javascript so I am sorry if my question is a simple one. anyway,
I'm writing a code that creates a batch file in order to open a certain file in the default application defined by the operation system. For example, pdf files will open in Adobe's Acrobat Reader. To do so, I'm using the FileSaver.js
And my code goes like this:
$(document).ready(function() {
$('#openPdf').click(function() {
saveAs(data2blob(
myPDF),
'openPDF.bat');
});
});
function data2blob(data, isBase64) {
var chars = "";
if (isBase64)
chars = atob(data);
else
chars = data;
var bytes = new Array(chars.length);
for (var i = 0; i < chars.length; i++)
bytes[i] = chars.charCodeAt(i);
var blob = new Blob([new Uint8Array(bytes)],
{type: "text/plain;charset=utf-8"});
return blob;
}
with myPDF being a string to a specific file I want to open which I'm certain of its existence. When I test my code on IE, it works perfectly. However, when I try it on Firefox, the file created is 'openPDF.bat.sdx' instead of 'openPDF.bat'. I've checked that it is indeed the same file only with the added extension. Does anyone have an idea what is the reason for this? and how can I overcome it?
I finally managed to download the file in Firefox the same way as in IE. I've made one minor change in the code: when creating the blob variable in the data2blob function I've used:
var blob = new Blob([new Uint8Array(bytes)], {type: "application/octet-stream"});
Not sure, what is the difference between the way it was before and how it is now, except of the result of course.

Using FileReader to read cloud images in Android browser

I have the following javascript which provides an image upload button and displays the image:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#target').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
The full jsfiddle is here:
http://jsfiddle.net/6NXwv/
This code works on every mobile browser I've tried except for the stock Android browser. Specifically images only fail to load if they are stored remotely but appear in the gallery (for example synced facebook or picasa images). Now I know FileReader is only for LOCAL files however chrome browser, opera, and firefox mobile have no issues.
I checked the FileReader error code, it appears that gallery images from facebook/picasa return NOT_FOUND_ERR:
https://developer.mozilla.org/en-US/docs/Web/API/FileError
If this is a case of FileReader not able to read remote files why does it work in all other mobile browsers?
I can't find anyone else having this exact issue, everything I google keeps returning this result:
Issue with stock Browser picking photos from Gallery
However the mime-type appears to be detected correctly. The mime-type shows up and the filename shows the correct name but the actual data isn't there (also File.size reports '0'). I've been able to recreate this on the stock android browser on 4.4 and 4.3. Haven't tested older versions.
In short when selecting photos via the gallery, local files and new images taken with the camera load correctly but remote facebook/picasa files (on 4.4 at least they have little fb/picasa icons on their thumbnails in the gallery) do not load. Only occurs in stock browser.
The error you face have 2 explanation.
First explanation is that the files "Images" that you tried to read with HTML5 API FileReader are looked or on use by other applications "like Facebook or Picasa" and in this case you can do nothing about it from js unless you have physical access to the hardware "Phone".
second explanation which is more likely is some browsers can't fire the event onload of FileReader because they are not fully supporting this HTML5 API. you can read more about this in caniuse website. And that can be solve by changing the event onload to onloadend.
here is how your code should be :
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result);
};
reader.readAsDataURL(file);
here is example: jsfiddle
here is Demo: Demo FileReader Html5
<input id="fileinput" name="arquivo[]" type="file" multiple="multiple" onchange="FileDetails()"/>
<var id="file_List"></var>
<button type="button" onclick="Click()">Click Me!</button>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script>
// simple routine to put content of file input files into memory
G_Array = [];
G_Cont_Upload = 0;
function Click()
{
var a = 1; // this is only to check the content of global variable as google chrome does not stop inside f_ReadFile
}
function FileDetails()
{
var file_arr = [];
if (typeof (FileReader) != "undefined")
{
var files = $('#fileinput')[0].files;
var reader = [];
for (var i = 0; i < files.length; i++)
{
var FileDet = files[i];
var name = FileDet.name;
var Size = FileDet.size;
var Obj = {Name: FileDet.name, SizeInicial : FileDet.size};
G_Array.push(Obj);
reader[i] = new FileReader();
function f_ReadFile(e)
{
var content = e.target.result;
G_Array[G_Cont_Upload].SizeAtual = content.length;
G_Array[G_Cont_Upload].Content = content; // content base 64
G_Cont_Upload++;
}
reader[i].onload = f_ReadFile;
reader[i].readAsDataURL(FileDet);
}
}
else
{
alert("This browser does not support HTML5 FileReader.");
}
}
</script>
</body>

Reading client side text file using Javascript

I want to read a file (on the client side) and get the content in an array. It will be just one file. I have the following and it doesn't work. 'query_list' is a textarea where I want to display the content of the file.
<input type="file" id="file" name="file" enctype="multipart/form-data"/>
<script>
document.getElementById('file').addEventListener('change', readFile, false);
function readFile (evt) {
var files = evt.target.files;
var file = files[0];
var fh = fopen(file, 0);
var str = "";
document.getElementById('query_list').textContent = str;
if(fh!=-1) {
length = flength(fh);
str = fread(fh, length);
fclose(fh);
}
document.getElementById('query_list').textContent = str;
}
</script>
How should I go about it? Eventually I want to loop over the array and run some SQL queries.
If you want to read files on the client using HTML5's FileReader, you must use Firefox, Chrome or IE 10+. If that is true, the following example reads a text file on the client.
your example attempts to use fopen that I have never heard of (on the client)
http://jsfiddle.net/k3j48zmt/
document.getElementById('file').addEventListener('change', readFile, false);
function readFile (evt) {
var files = evt.target.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function(event) {
console.log(event.target.result);
}
reader.readAsText(file)
}
For IE<10 support you need to look into using an ActiveX Object like ADO.Stream Scripting.FileSystemObject http://msdn.microsoft.com/en-us/library/2z9ffy99(v=vs.85).aspx but you'll run into a security problem. If you run IE allowing all ActiveX objects (for your website), it should work.
There is such thing as HTML5 File API to access local files picked by user, without uploading them anywhere.
It is quite new feature, but supported by most of modern browsers.
I strongly recommend to check out this great article to see, how you can use it.
There is one problem with this, you can't read big files (~400 MB and larger) because straight forward FileAPI functions attempting to load entire file into memory.
If you need to read big files, or search something there, or navigate by line index check my LineNavigator, which allows you to read, navigate and search in files of any size. Try it in jsFiddle! It is super easy to use:
var navigator = new FileNavigator(file);
navigator.readSomeLines(0, function linesReadHandler(err, index, lines, eof, progress) {
// Some error
if (err) return;
// Process this line bucket
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
// Do something with it
}
// End of file
if (eof) return;
// Continue reading
navigator.readSomeLines(index + lines.length, linesReadHandler);
});
Well I got beat to the answer but its different:
<input type="file" id="fi" />
<button onclick="handleFile(); return false;">click</button>
function handleFile() {
var preview = document.getElementById('prv')
var file = document.getElementById('fi').files[0];
var div = document.body.appendChild(document.createElement("div"));
div.innerHTML = file.getAsText("utf-8");
}
This will work in FF 3.5 - 3.6, and that's it. FF 4 and WebKit you need to use the FileReader as mentioned by Juan Mendes.
For IE you may find a Flash solution.
I work there, but still wanted to contribute because it works well: You can use the filepicker.io read api to do exactly this. You can pass in an dom element and get the contents back, for text or binary data, even in IE8+

Categories

Resources