Certain PDF files won't open - javascript

I'm having a weird issue I created an app to open PNG and PDF's. The problem is when I try to open PDF files larger than 2,000 Kb it will not display, however PNG's have no problem. I'm confused as too why this is.
<html lang="en"><head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" media="all" href="styles.css">
</head>
<body>
<ul>
</ul>
<fieldset>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000">
<div>
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="file-select[]" multiple="multiple">
<div id="filedrag" style="display: block;">or drop files here</div>
</div>
<div id="submitbutton" style="display: none;">
<button type="submit">Upload Files</button>
</div>
<div id="sortbutton">
<button type="submit">Submit</button>
</div>
<div id="resetbutton">
<button type="submit">Reset</button>
</div>
</fieldset>
</form>
<div id="messages">
</div>
<script src="filedrag.js"></script>
</body></html>
var files;
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
}
}
// output file information
function ParseFile(file) {
// display an image
if (file.type.indexOf("application") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
files.push("<p align=left><strong>" + file.name + ":</strong><br />" +
'<object data="' + e.target.result + '"></object></p>');
}
reader.readAsDataURL(file);
}
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
files.push("<p align=left><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" height="500px" width="500px"></p>');
}
reader.readAsDataURL(file);
}
}
function sortFiles() {
files.sort().reverse();
for (var i = 0; i < files.length; ++i) {
Output(files[i]);
}
}
function resetWindow(){
window.location.reload(true)
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton"),
sortbutton = $id("sortbutton"),
resetbutton = $id("resetbutton");
files = new Array();
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
submitbutton.addEventListener("click", sortFiles , false); //style.display = "none";
sortbutton.addEventListener("click", sortFiles , false);
resetbutton.addEventListener("click", resetWindow , false);
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
As I said you try to post a PDF file larger than 2000 Kb it will not display, PNG however will display

I fixed it I hardcoded the path to display the Files

I had the same issue like yours and I resolved in this way:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="height: 100%;">
<button onclick="getFile(event)">Get File</button>
<input id="pdfInputFile" type="file" accept="application/pdf" style="display:none" onchange="loadPDF(this);" />
<object id="pdfViewer" type="application/pdf" style="height:100%; width:100%;border:solid 1px" >
</object>
</body>
<script>
function getFile(e) {
e.preventDefault();
document.getElementById("pdfInputFile").click();
}
function loadPDF(input) {
if (input.files && input.files[0]) {
showFile(input.files[0])
}
}
function showFile(blob){
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
var newBlob = new Blob([blob], {type: "application/pdf"});
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(newBlob);
document.getElementById("pdfViewer").setAttribute('data', data);
setTimeout(function(){
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}
</script>
</html>

Related

Using a single .txt file to populate many text areas within an HTML form

I am making an entirely client-side html file that exports .txt files based on the contents of its many text areas and text fields.
The problem arise when I try to import that same .txt file back into the page, as of now its populates all the text areas with the same content while I would like it to only be populated with specific stuff.
E.G. text area 1, 2, and 3 have their contents added to a single .txt file, upon importing it all text areas have content from text area 1, 2 and 3.
Here is my current HTML code
(function() {
var input = document.getElementById("fileinput");
input.addEventListener("change", loadFile, false);
function loadFile() {
var file, fr;
if (typeof window.FileReader !== 'function') {
alert("The file API isn't supported on this browser yet.");
return;
}
if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText() {
document.getElementById("input1").value = fr.result;
document.getElementById("input2").value = fr.result;
document.getElementById("input3").value = fr.result;
}
}
})();
function saveFormAsTextFile()
// Based on https://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/
{
var textToSave =
document.getElementById('input1').value + '\n' +
document.getElementById('input2').value + '\n' +
document.getElementById('input3').value
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("input1").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<button onclick="saveFormAsTextFile()">Save</button></strong>
<form name="mainForm" method="get" id="Main">
<p>input 1:<textarea id="input1" cols="20" rows="2"></textarea>
<p>input 2:<textarea id="input2" cols="20" rows="2"></textarea>
<p>input 3:<textarea id="input3" cols="20" rows="2"></textarea>
<p>
<div>
<label for="file">Choose file to upload</label>
<input type="file" id='fileinput' accept=".txt">
</div>
</form>
</body>
</html>
You join text with \n in
var textToSave =
document.getElementById('input1').value + '\n' +
document.getElementById('input2').value + '\n' +
document.getElementById('input3').value
So just reverse step it with .split('\n')
function receivedText() {
var data = fr.result.split('\n');
document.getElementById("input1").value = data[0];
document.getElementById("input2").value = data[1];
document.getElementById("input3").value = data[2];
}
Demo
(function() {
var input = document.getElementById("fileinput");
input.addEventListener("change", loadFile, false);
function loadFile() {
var file, fr;
if (typeof window.FileReader !== 'function') {
alert("The file API isn't supported on this browser yet.");
return;
}
if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText() {
var data = fr.result.split('\n');
document.getElementById("input1").value = data[0];
document.getElementById("input2").value = data[1];
document.getElementById("input3").value = data[2];
}
}
})();
function saveFormAsTextFile()
// Based on https://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/
{
var textToSave =
document.getElementById('input1').value + '\n' +
document.getElementById('input2').value + '\n' +
document.getElementById('input3').value
var textToSaveAsBlob = new Blob([textToSave], {
type: "text/plain"
});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("input1").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event) {
document.body.removeChild(event.target);
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<button onclick="saveFormAsTextFile()">Save</button></strong>
<form name="mainForm" method="get" id="Main">
<p>input 1:<textarea id="input1" cols="20" rows="2"></textarea>
<p>input 2:<textarea id="input2" cols="20" rows="2"></textarea>
<p>input 3:<textarea id="input3" cols="20" rows="2"></textarea>
<p>
<div>
<label for="file">Choose file to upload</label>
<input type="file" id='fileinput' accept=".txt">
</div>
</form>
</body>
</html>
Sidenote: file uploading in your code doesn't work in safari
It appears in the function receiveText, you set all three elements to equal the same string, 'fr.result".
You need a way to devide up the content of the txt so you can split it into multiple strings and assign each sub-string to a separate field.
Maybe a simple XML structure would help.

How to delete from an object FileList

The function of this code, the preview image is displayed after selecting the file. Also internally, each key and value is inserted into the FileList object.
Each image displayed as a preview has a delete button. So, when you press it, the image disappears from the screen, and internally, I want to delete the corresponding key and value from the FileList object. I knew that I could delete from Object, like a " delete Object.key ; " However, in this case, this does not work effectively. Perhaps there are other different solutions to it. Please let me know if you know if
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<style>
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<form id='form' action="data.php" method="post" enctype="multipart/form-data">
<input type="file" id="files" name="files[]" multiple />
<button class="show">Butoon</button>
</form>
<output id="list"></output>
<script>
$('output').on('click','.del',function(){
var id = $(this).prev().attr('id');
id = id.split("_");
id= id[1];
var x = document.getElementById("files").files;
if(id in x) {
delete x[' + id + '];  //This line is a problem.
}
console.dir(x);
$(this).parent().replaceWith();
});
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile, num) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<div class="view"><img id ="img_' + num + ' " class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/><div class="del">×</div></div>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f, i);
reader.readAsDataURL(f);
}
console.dir(files);
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
Replace delete x[' + id + ']; with:
x.splice(id,1);

Wrong message , File uploaded but still "Maximum request length exceeded"

I have wrote an upload file method in javascript to upload big files it slpits thefiles in blobs and reattach the blobs in server side again so I can upload big files but there is a problem... after the upload is done and I receive the file in server side (the fileuploads completely), it gives me this Maximum request length exceeded
<!DOCTYPE HTML>
<html>
<head id="Head1" runat="server">
<title>uploading file using jquery with generic handler ashx</title>
<link id="Link2" rel="stylesheet" runat="server" media="screen" href="~/fileupload.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<%--<script src="JavaScript1.js" type="text/javascript"></script>--%>
<script src="MyScript.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<div id="uploadFile">
<div class="fileuploadDiv">
<div class="status"></div>
<input type="file" name="files[]" multiple="multiple" id="files" class="fileSelect" />
<input type="submit" value="Upload" class="button" id="btnUpload" />
<%--<div id="progressbar" class="progress"></div>--%>
<div class="progress" id="progressbar">
<div class="bar" id="bar"></div>
<div class="percent" id="percent">0%</div>
</div>
<div id="messages"></div>
</div>
</div>
</form>
</body>
MyScript.js
$(document).ready(function () {
$("#btnUpload").click(function (evt) {
var blobs = [];
var fl = document.getElementById("files");
var L = fl.files.length;
var elem = document.getElementById("bar");
var per = document.getElementById("percent");
for (var i = 0; i < L ; i++) {
var file = fl.files[i];
var bytes_per_chunk = 3*1024*1024; //1048576
var start = 0;
var end = bytes_per_chunk;
var size = file.size;
var j = 1;
while (start < size) {
//push the fragments to an array
blobs.push(file.slice(start, end));
start = end;
end = start + bytes_per_chunk;
}
while (blob = blobs.shift()) {
var fileName = file.name;
var fileType = file.type;
var fileSize = file.size / 100;
var rec = 0;
rec = blob + rec;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'Handler.ashx', false);
xhr.onload = function () {
alert("in for");
elem.style.width = j + "%";
per.innerHTML = j + "%";
j++;
rec = 0;
}
xhr.setRequestHeader('X_FILE_NAME', fileName);
xhr.setRequestHeader('Content-Type', fileType);
xhr.send(blob);
}
}
});
});
Handler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace test
{
public class Handler : IHttpHandler
{
int fileCount = 0;
public static void AppendAllBytes(string path, byte[] bytes)
{
//argument-checking here.
try
{
using (var stream = new FileStream(path, FileMode.Append))
{
stream.Write(bytes, 0, bytes.Length);
}
}
catch (Exception)
{
throw;
}
}
public void ProcessRequest(HttpContext context)
{
try
{
byte[] buffer = new byte[context.Request.ContentLength];
context.Request.InputStream.Read(buffer, 0, context.Request.ContentLength);
string fileName = context.Request.Headers.Get(11);
AppendAllBytes(context.Server.MapPath("~/upload/" + fileName), buffer);
}
catch (Exception)
{
throw;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I Solved it Finally
the problem is the "Submit" that I changed it to button so itdoes not send the whole file also after submitting the button
I did this :
input type="button" value="Upload" class="button" id="btnUpload" />
instead of
input type="submit" value="Upload" class="button" id="btnUpload" />

Uncaught SyntaxError: Unexpected token <

I have been following a video tutorial on youtube for an AJAX upload, i know a fair amount of javascript, jquery, etc but this has me stumped.
my code is below, can anyone enlighten me as to why this is happening when i try to uploade more than one file or in some cases 1 file.
I have included my code below, its not perfect as i said i was follwoing along with a video tutorial.
<?php
if (!empty($_FILES['file']))
{
foreach($_FILES['file']['name'] as $key=>$name)
{
if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'] [$key], "uploads/{$name}"))
{
$uploaded[] = $name;
}
}
if (!empty($_POST['ajax']))
{
die(json_encode($uploaded));
}
}
?>
<html>
<head>
<title></title>
<script type="text/javascript" src="upload.js"></script>
</head>
<style type="text/css">
#upload_progress {display: none;}
</style>
<body>
<div id="uploaded">
<?php
if(!empty($uploaded))
{
foreach ($uploaded as $name) {
echo '<div>'.$name.'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" multiple="multiple">
<input type="submit" id="submit" value="upload">
</form>
</body>
</html>
And my JS file is
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for (var i = 0; i < fileInput.files.length; ++i)
{
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event) {
if (event.lengthComputable)
{
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes())
{
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + '%'));
}
});
request.upload.addEventListener('load', function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert("Upload Failed");
});
request.addEventListener('readystatechange', function(event) {
if (this.readyState == 4) {
if (this.status == 200)
{
var links = document.getElementById('uploaded');
console.log(this.response);
var uploaded = JSON.parse(this.response);
var div, a;
for (var i = 0; i < uploaded.length; i++)
{
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'uploads/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
} else {
console.log("error" + this.response);
}
}
});
request.open('POST', 'index.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
Initially the video had me using eval for the variable uploaded, i changed this to JSON.parse, i don't want a quick fix but rather an answer as to why this isn't working?
Thanks
Ben
I found out what the problem was, inside the php.ini file there is a size restriction on my server for file uploads, i increased that and it works fine now.
Anyone else who has the same problem check your upload size!

javascript ajax upload system check condition

I was following a tutorial about how to make an javascript/ajax upload system with progress (%) indicator . I have successfully added a css progress bar indicator to it .
But i have a problem that i can't solve is how to put to condition of upload like: type, file size, file is set, ....
here is my code (upload.php)
<?php
foreach($_FILES['file']['name'] as $key => $name){
if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])){
die(json_encode($uploaded));
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="upload.js"></script>
</head>
<body>
<div id="uploaded">
<?php
if (!empty($uploaded)){
foreach ($uploaded as $name){
echo '<div>',$name,'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" />
<input type="submit" id="submit" value="upload" />
</form>
and this is the javascript file (upload.js):
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes()){
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +' %'));
document.getElementById("loading-progress-17").style.width= Math.round(percent * 100) +'%';
}
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event){
alert('Upload failed');
});
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if(this.status == 200){
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
for (var i = 0; i < uploaded.length; ++i){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'files/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
}else{
console.log('server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
I just need and example of how to check file size is less than 50MB and i can do the other checks my self i just don't know how to check condition in this upload system.
Thanks in advance
If you want to check something like the size, you can realize it with your code easily:
Take a look at these lines in your code:
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}
This is where the files are added to the FormData which is then submitted to the server. You can add the conditions here, e.g. a size check:
for (var i = 0; i < fileInput.files.length; ++i){
//file.size is given in bytes
if(fileInput.files[i].size <= MAX_FILESIZE_IN_BYTES){
data.append('file[]', fileInput.files[i]);
}
}
I hope this helps.

Categories