Preview .doc/.docx/.pdf files before uploading to server - javascript

I'm using HTML5 File API to get some document(.doc/.docx/.pdf) uploaded. And I want to show that document preview before uploading it to server. Is there any way to do such thing on client side?
P.S. Google Docs Viewer isn't ok, because it requires document to be accessible from the internet.

I have tried to create little example and that would display PDF Preview before uploading PDF file.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript PDF Viewer Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function PreviewImage() {
pdffile=document.getElementById("uploadPDF").files[0];
pdffile_url=URL.createObjectURL(pdffile);
$('#viewer').attr('src',pdffile_url);
}
</script>
</head>
<body>
<input id="uploadPDF" type="file" name="myPDF"/>
<input type="button" value="Preview" onclick="PreviewImage();" />
<div style="clear:both">
<iframe id="viewer" frameborder="0" scrolling="no" width="400" height="600"></iframe>
</div>
</body>
</html>

Not sure if anyone still checks this thread, but i thought i'd share what i did.
Directly showing a preview isn't possible, but you can create a blob object of the selected file. Something like this (jQuery):
$('#input').change(function (event) {
var file = URL.createObjectURL(event.target.files[0]);
$('element').append('' + event.target.files[0].name + '');
});
This link will open a new browser tab and shows/downloads the file. This isn't really pretty but it works.
Here's an example: https://jsfiddle.net/j9gw023b/3/

No. This is not possible.
You want the browser to view a datafile it shouldn't. You have Office or PDF viewers (OK, granted, PDF ssems to be inside browsers now...) to view your data files.
If you want to show a preview in the browser, you have to upload it first and store it in a "for-preview" dir or something. When OK, move it to its final destination, otherwise, delete.

The File API will allow you to read the data from the file, but then you have the trouble of parsing it and rendering it. Mozilla have released a JavaScript PDF viewer, but I'm not aware of anything for MS Office files.

Back in the days you were able to do something like that:
<object data="word.doc">You do not have Word installed on your machine</object>
Not sure if this is still supported, but if so, you could use JS to inject that object onto the page to preview it.

Ajax upload your file,then after uploaded return path name and preview it.
blueimp's jQuery-File-Upload was great for me.
you can view its basic plugin.
https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin

You can do it with pdf, here is the tutorial:
https://usefulangle.com/post/87/javascript-preview-pdf-during-upload
Don't know if it is possible for doc/docx

You can do it using this web component: https://avipunes.github.io/file-viewer/
This web component under the hood uses some microsoft embedding endpoint:
https://view.officeapps.live.com/op/embed.aspx?src=${fileURI}
you can see an example here:
https://view.officeapps.live.com/op/embed.aspx?src=https://file-examples-com.github.io/uploads/2017/02/file_example_XLS_10.xls

Related

PDF-Lib Modify PDF Downloadable

Currently implementing the PDF-Lib Library for my project to modify PDFs
Source: https://pdf-lib.js.org/#examples
And it is working very well, but the modified PDFs are saved on the server.
I am searching for the opportunity that the pdfs which modified will directly downloaded for the user.
Thanks!
If you follow the examples where the ones that download to client like https://jsfiddle.net/Hopding/64zajhge/1/ have
<script src="https://unpkg.com/downloadjs#1.4.7"></script>
</head><body>
...
Instructions
<button onclick="modifyPdf()">Modify PDF</button>
...
<script>
async function modifyPdf()
...
// Trigger the browser to download the PDF document
download(pdfBytes, "pdf-lib-output.pdf", "application/pdf");
however that may need some secured configuration, way beyond this single question.

Saving .json file using javascript

I want to save json file to my application's directory using javascript. how to do it? my code only opens a new tab when you click download button and display the content of my json file. I am allowed to use client-side scripting only. I've tried this code but not working.
NOT WORKING CODE:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("location", true);
s.WriteLine(json);
s.Close();
Here's my code..
HTML CODE:
<!doctype html>
<html manifest="survey.manifest">
<head>
<title>Offline Survey Application</title>
<link rel="stylesheet" href="styles/survey.css" type="text/css">
<script type="text/javascript" src="scripts/survey.js"></script>
</head>
<body>
</body>
</html>
Javascript code
window.onload=function myFunction()
{
var btn=document.createElement("BUTTON");
btn.setAttribute('id', 'dButton');
btn.setAttribute('value', 'download');
var t=document.createTextNode("DOWNLOAD");
btn.appendChild(t);
document.body.appendChild(btn);
btn.onclick=function clickedFunction(){
var url = "http://localhost/JSONFiles/survey.json";
window.open(url, 'download');
}
};
thanks in advance friends! :)
What you are trying to do would kill a lot of kittens.
For safety reasons, a web page cannot use activeX objects on a whim, nor access the local computer resources like file system in any way except what is allowed by standard (basically the cookies and local storage files).
That would allow any Russian hacker and his rabid dog to wreak havoc on computers all over the planet.
You can, however, try to use local storage if your json files are not too bulky and you don't expect to reuse them from another application.
If you plan on downloading json files, just point to them (i.e. put a link to whatever .json file somewhere on your page) and when the user clicks on such a link the browser will pop a save requester to let the user free to save the files in a location of his/her choosing.
If all you're trying to do is get a file on your server to download automatically instead of be viewed in the browser, you just need to set the Content-Disposition header the file is sent to the client with to "attachment". The easiest way to do that is to modify the config files for whatever server your using to add a rule for files of type .json. The exact methodology will differ depending on your server, though.

Load data from text file with ajax/javascript into html problems

I want to load data from this text file that is in the same folder as the html file on my computer but it won't work. In process of learning Ajax and put together this little test for myself test.html and the text file test.txt. Any advice please, would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script>
function loadData()
{
var test;
test=new XMLHttpRequest();
test.onreadystatechange=function()
{
if (test.readyState==4 && test.status==200)
{
document.getElementById("test").innerHTML=test.responseText;
}
}
test.open("GET","test.txt",true);
test.send();
}
</script>
</head>
<body>
<div id="test"></div>
<button type="button" onclick="loadData()">Get data</button>
</body>
</html>
When I press the button, nothing happens. On the site where I saw a similar example the data from the text file is displayed above the button.
The problem is likely to be that you're accessing the files directly on your local system; web browsers have been designed not to allow this in order to prevent saved web pages loading personal files from your disks and uploading them to remote servers. In order to make it work, you'll need to run a web server locally and use that to view the files. I recommend the Apache web server, which is flexible and can be used on Windows, Linux or OSX.

Write to text file in html

I wanted to try giving an output to a file using a Small screen on HTML. Everytime I click on the button I want the text in the file to be replaced. This is the code I wrote:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>This is Web App</title>
</head>
<script>
function createDoc()
{
var doc=document.open("answer.txt","replace");
var txt="<html><body>You clicked Allow</body></html>";
doc.write(txt);
doc.close();
}
function createDoc2()
{
var doc=document.open("answer.txt","replace");
var txt="<html><body>You clicked Deny</body></html>";
doc.write(txt);
doc.close();
}
</script>
<body>
<h1> This is the visitor at your house</h1>
<img src = "./images/chef.gif" width="130" height="101" />
<br />
<button name="Yes" type="button" onclick="createDoc()">Allow! </button>
<button name="No" type="button" onclick="createDoc2()">Deny! </button>
</body>
</html>
I know it is not the correct way to do it but am trying to learn. Please help me and point out my mistakes and tell me how to correct them if possible. I know there might be plenty. I am just trying to teach myself at this point. Your help is much appreciated.
If you just want to download a file generated by your page, this question may help:
Download data url file
The idea is that you need to encode your data as base64 (not hard, modern browsers support btoa) and direct the browser to open it. If you trick it by giving the file a mime-type it doesn't know how to open (such as application/octet-steam), it will download the file instead of displaying it.
The problem with this solution is that you cannot name the file.
If you want to name the file, I'd POST the data to your webserver, write it to a file on the server, then do a window.open with the path to the file. This will allow you to download the file in question.
There's a draft in progress to allow Javascript to write to a file directly, but this file will be in a sandboxed location that users don't have direct access to. This is only for web-apps to store large amounts of data on the client. From your question, this is likely not what you want. Try one of the above solutions.

loading an image through javascript

is there a way to load the full binary of an image in javascript?
what i want to do is to allow the user to preview an image before uploading it.
ie the user selects an image on his local drive (C:\image.jpg) , view it, and decides to upload or cancel.
i tried to set the source to the image path, but it didn't work since it is outside the webapplication project folder.
any help?
thx for your posts, but i ended up creating a temp folder on the server that stores the uploaded image using ajax. and when the user saves the data, the image is moved to another location, and the temp folder is deleted.
You can do something like this:
<img id="preview" src="" style="display:none;" />
<form>
....
<input type="file" id="file" />
....
</form>
<script type="text/javascript">
var file = document.getElementById("file");
var img = document.getElementById("preview");
file.onchange = function(){
img.src = file.value;
img.style.display = 'block';
};
</script>
There is no easy way, what You could do:
Preload image with some ajax file uploader to temp area and then let user decide
Use some third party written solution (f.ex. some flash component)
Here there is also similar question:
is it possible to preview local images before uploading them via a form?
You need server cooperation to access the image binary data. You won't be able to use the "Upload Form" to access the file info without uploading it to a server.
You could however do something like tell the user to paste the source binary data of the image in a textarea or something, then you can use JavaScript to load that binary data and display the actual image.
This is available in some browsers via the HTML5 file access API. Here is the Firefox documentation for file access.
As answered several times, you can't do this with plain HTML/JavaScript due to security restrictions. You need to send the image anyway. You can however handle this using a Java Applet since it runs entirely at the client machine and offers more control than HTML/JS. There are several free and ready-to-use ones. JumpLoader looks good and some major sites also uses it. With Flash it should also be possible, but I am not sure which ones offers this functionality. Check/tryout some Flash Multi File Uploaders.

Categories