I am making an application that brings up a preview of PDF files. Embedding with an embed element works well for small PDF files but fails for larger PDF files because of the size limits for data urls. I'm looking for a way to use the browser's native PDF viewer to view PDF files but without using data urls.
My code currently looks something like the following:
<script>
function addToCard(input) {
if (input.files.length <= 0) return;
let fileReader = new FileReader();
fileReader.onload = async function () {
pdfCard.src = fileReader.result;
};
fileReader.readAsDataURL(input.files[0]);
}
</script>
<input type=file oninput="addToCard(this)" />
<embed id=pdfCard style="width:100%;height:100%" />
Example. The original PDF is here.
You could use URL.createObjectURL() on the PDF. It also creates a URL representing the object; however, the difference between an object URL and a data URL is that, while a data URL contains the object itself, an object URL is a reference to the object, which is stored in memory. This means that object URLs are significantly shorter than data URLs and take less time to create.
There are two drawbacks to this approach that may prevent you from using it. The first is that an object URL will only work on the page on which it was created. Attempting to use an object URL on a different page will not work. If you need to access this URL anywhere other than the page it was created on, this approach will not work.
The second is that object URLs keep the object for which they were created stored in memory. You have to revoke the object URL when you are done using it with the URL.revokeObjectURL() method, otherwise it will cause a memory leak. This means that you might have to add some extra code that revokes the object URL once the PDF is loaded. This example may be helpful.
The implementation might look something like this:
function addToCard(input) {
if (input.files.length <= 0) return;
pdfCard.src = URL.createObjectURL(input.files[0])
// gonna have to call revokeObjectURL eventually...
}
Related
Short version
I have a webapp using Magnolia, I need to upload a comment with posibility of multiple files, I want to use AJAX, before saving the files as assets I want to be able to check the user's permission, I figured I need a custom Java-based REST endpoint, I made it work, but I have issues saving "jcr:data" into an asset.
Long version
I have a webapp, I have registered users (using PUR), I have different roles for users (for simplicity let's say User and Editor) and I have a Post and a Comment content types. Every User can create a Post and add files, every Post holds the creator's UUID, array of Comment UUIDs and array of file UUIDs (from Assets app), every Post has a comment section and every Comment can have files attached (zero or multiple) to it. Every Editor can post a comment to every Post, but Users can only post comments to their own Posts.
My form for comments looks something like this:
<form action="" method="post" id="comment-form" enctype="multipart/form-data">
<input type="file" name="file" id="file" multiple />
<textarea name="text"></textarea>
<button type="button" onclick="sendComment();">Send</button>
</form>
I tried using Javascript model to process the data and I was able to save the asset correctly, however only one. I couldn't access the other files in the model.
I tried solving it (and improving user experience) by using AJAX and a REST endpoint. I opted not to use the Nodes endpoint API, because I didn't know how to solve the permission issue. I know I can restrict access to REST for each role, but not based on ownership of the Post. So I created my own Java-based endpoint (copied from documentation).
In the sendComment() function in Javascript I create an object with properties like name, extension, mimeType, ..., and data. I read in the documentation that you should send the data using the Base64 format, so I used FileReader() to accomplish that:
var fileObject = {
// properties like name, extension, mimeType, ...
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// this part is easy
};
xhttp.open("PUT", "http://localhost:8080/myApp/.rest/assets/v1/saveAsset", true);
xhttp.setRequestHeader("Content-type", "application/json");
var reader = new FileReader();
reader.onload = function() {
fileObject.data = reader.result;
// I also tried without the 'data:image/png;base64,' part by reader.result.split(",")[1];
xhttp.send(JSON.stringify(fileObject));
};
reader.readAsDataURL(file); //where file is the value of the input element.files[i]
In Java I created a POJO class that has the same properties as the javascript object. Including a String data.
The code for the endpoint looks like this:
public Response saveAsset(Asset file) {
// Asset is my custom POJO class
Session damSession;
Node asset;
Node resource;
try {
damSession = MgnlContext.getJCRSession("dam");
asset = damSession.getRootNode().addNode(file.getName(), "mgnl:asset");
asset.setProperty("name", file.getName());
asset.setProperty("type", file.getExtension());
resource = asset.addNode("jcr:content", "mgnl:resource");
InputStream dataStream = new ByteArrayInputStream(file.getData().getBytes());
ValueFactory vf = damSession.getValueFactory();
Binary dataBinary = vf.createBinary(dataStream);
resource.setProperty("jcr:data", dataBinary);
resource.setProperty("fileName", file.getName());
resource.setProperty("extension", file.getExtension());
resource.setProperty("size", file.getSize());
resource.setProperty("jcr:mimeType", file.getMimeType());
damSession.save();
return Response.ok(LinkUtil.createLink(asset)).build();
} catch (RepositoryException e) {
return Response.ok(e.getMessage()).build(); //I know it's not ok, but that's not important at the moment
}
}
The asset gets created, the properties get saved apart from the jcr:data. If I upload an image and then download it either by the link I get as a response or directly from the Assets app, it cannot be opened, I get the format is not supported message. The size is 0, image doesn't show in the Assets app, seems like the data is simply not there, or it's in the wrong format.
How can I send the file or the file data to the Java endpoint? And how should I receive it? Does anybody know what am I missing? I honestly don't know what else to do with it.
Thank you
The input stream had to be decoded from Base64.
InputStream dataStream = new ByteArrayInputStream(Base64.decodeBase64(file.getData().getBytes()));
...and it only took me less than 3 months.
Noticed it after going through the source code for REST module that for unmarshalling Binary Value it had to be encoded to Base64, so I tried decoding it and it started to work.
After browsing around the internet for a few hours to find a solution, I found out a few methods of getting the information from a filereader, but not quite to what I need.
function submitfile() {
var reader = new FileReader();
reader.readAsDataURL(document.getElementById("filesubmission").files[0]);
reader.onload = function (REvent) {
document.getElementById("outputcontent").innerHTML = "<iframe width='100%' id='outputdata' scrolling='yes' onload='resizeIframe(this)' src='"+REvent.target.result+"'></iframe>";
};
}
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
That is the code that I'm using after a user selects a file, which I allow .html, .htm, .txt, or .xml. The Iframe is then resized to match the content. I have that functionality working, however I need to have a method of replacing text in the iframe with certain values that the user provides in <input> tags earlier. An example would be I need to be able to replace "[c1]" in the file the user provides with a client's name, such as "John Smith".
The way I would prefer to do this would be through the content of the file itself, rather than using a source in an iframe or data in an object. If I can get this into the original file itself where it can be edited, that would solve the problem.
I need to be able to do this without the use of jQuery or other plugins, since this is a local file that should be able to work standalone as a tool for my client.
Use the DOMParser to parse the reader's result:
var doc = (new DOMParser).parseFromString(reader.result,"text/html");
or any other mime type,
Then, update the some nodes within the doc based on the inputs you mention.
Then use the iframe's contentDocument to adopt the node using document.adoptNode. That will return the node with its ownerDocument pointing to the iframe. Lastly append it to the iframe's body.
I have a file upload that saves images as .png on the server and the link in a mysql database. To show thumbnails of the image before uploading I have a function that convertes the file list object to a preview pic. Now I want the user to edit the file selection later. For that I need to load the images from the server back as thumbnails. I think the best way to do this is to convert the file path stored in the database to a file object and apply this object to the function that creates the thumbnails that I don't need to rewrite this function.
So my question is how can I convert my stored image links to a file list object?
Edit:
upload:
user selection -> file object -> base 64 -> blob -> display blob -> (maybe) edit -> upload selection as base 64 to server -> base 64 to .png -> save pic -> save link
later edit selection by user(how to do?):
saved link -> file object -> base 64 -> blob -> display blob -> (maybe) edit -> ...
saved link -> file object How to do? Possible? Better way?
I hope it's now clearer to understand.
If someone has an idea how to do this or a better way please answer.
(I know that you should show Code when asking a question but I don't think that it is necesarry to upload the whole upload function here)
You process is all frowned, so I may not answer correctly your question, but I'm pretty sure this is an X-Y problem.
Javascript File objects inherit from the Blob object.
From MDN :
A File object is a specific kind of a Blob, and can be used in any context that a Blob can.
Never convert a File to a base64 dataURL, if it's to convert it back to a Blob ; this makes no sense and only pollute the browser's memory.
To display a Blob (or a File) in the browser, from media elements, or iframes, use the URL.createObjectURL(blob) method. This will return a blobURI, that will be available only for the life time of the initiating page, and only for the user's browsers. In case of user uploaded Files, the file is not even copied to memory, and the uri returned is just a direct pointer to the file on the user's system.
inp.onchange = function(){
var url = URL.createObjectURL(this.files[0]);
var img = new Image();
img.onload = function(){
document.body.appendChild(this);
}
img.onerror = function(){
console.log('probably not a supported image file');
}
img.src = url;
}
<input id="inp" type="file" accept="image/*">
If you need to modify the image, you can do so by drawing the resulting image on a canvas.
Then, instead of exporting your canvas to a dataURI, directly use the toBlob method, which can be polyfilled.
To send you File/Blob on your server, send the File/Blob directly instead of its 30% heavier base64 string representation.
This can be done really easily thanks to the FormData API.
var xhr = new XMLHttpRequest();
xhr.onload = done;
var formData = new FormData();
formData.append('file', theFile, fileName);
xhr.open('POST', yourServer);
xhr.send(formData);
Then you can retrieve it server side just like any File uploaded through the basic Multipart/Form method.
I am reading a local CSV file using a web UI, and the HTML5 FileReader interface to handle the local file stream. This works great.
However, sometimes I want the file being read to be updated continuously, after the initial load. I am having problems, and I think it might have something to do with the FileReader API. Specifically, after the initial file load, I maintain a reference to the file. Then, when I detect that the size of the file has increased, I slice off the new part of the file, and get a new Blob object. However, there appears to be no data in these new Blobs.
I am using PapaParse to handle the CSV parsing, though I don't think that is the source of the problem (though it may be).
The source code is too voluminous to post here, but here is some pseudocode:
var reader = new FileReader();
reader.onload = loadChunk;
var file = null;
function readLocalFile(event) {
file = event.target.files[0];
// code that divides file up into chunks.
// for each chunk:
readChunk(chunk);
}
function readChunk(chunk) {
reader.readAsText(chunk);
}
function loadChunk(event) {
return event.target.result;
}
// this is run when file size has increased
function readUpdatedFile(oldLength, newLength) {
var newData = file.slice(oldLength, newLength);
readChunk(newData);
}
The output of loadChunk when the file is first loading is a string, but after the file has been updated it is a blank string. I am not sure if the problem is with my slice method, or if there is something going on with FileReader that I am not aware of.
The spec for File objects shouldn't allow this: http://www.w3.org/TR/FileAPI/#file -- it's supposed to be like a snapshot.
The fact that you can detect that the size has changed is probably a shortcoming of an implementation.
I want to use the HTML5 FileApi to read a SWF to an OBJECT (or EMBED, if it's better to do?).
My current code crashes on Chrome/Iron (the only stable browser which also supports the xmlhttprequest v2 FormData). I got it to read image data into a on-the-fly created IMG. But the object one crashes the current tab in the browser.
else if (file.type == "application/x-shockwave-flash") {
var show = document.createElement("object");
show.type = "application/x-shockwave-flash"
show.style.width = "100%";
show.style.height = "100%";
show.id = "thumb";
document.getElementById("thumbnails").appendChild(show);
var reader = new FileReader();
reader.onload = (function (aImg) {
return function (e) { aImg.data = e.target.result; };
})(show);
reader.readAsDataURL(file);
Do I really read to the object.data part? How is it done right? Anybody know? Or is this incomplete and I have to wait for better implementation?
A few things I'd recommend trying (in order of increasing complexity):
base64 encode the data with btoa and set it using a data: URI,
instead of creating the object using createElement, construct the <object> tag with all attributes as an HTML string (including the base64 advice above), then inject it into a DOM element with innerHTML,
create a reflector web service where you POST the swf content, it gives you a URL, then pass the URL off to the object,
similar to the previous, create a reflector web service where you POST the swf content, targeting a full-screen IFRAM as the target, have the service spits back an HTML doc including an <object> pointing back to the server.
The later of these options is more intense, and requires round-trips from the server that you'd probably want to avoid - just some more options you might want to consider.
ActionScript 3 has a Loader which may be useful as well. I don't know if it supports data: URI's, but if it does, you could write a boot loader SWF which runs the contents of the local swf file directly.