I'm using a 3rd party library which wants to load in a file via the HTML file system, as in:
<input id="fileupload" type="file" onchange="LoadAndDisplayFile(this.files[0])">
This works great, except I'd like to pass in a url to a file stored on the serverr rather than have the user upload a file.
I tried using:
var myFile = new File ("path/to/file");
with the hope that I'd then be able to pass myFile
into LoadAndDisplayFile()
but I get the following error:
Uncaught TypeError: Failed to construct 'File': 2 arguments required, but only 1 present.
I'm sure this is a noob question, but what am I missing here?
Did you know you can create files using JavaScript right inside your browser and have users download them? You can create files with a proper name and mime type and it only takes a few lines of code.
createObjectURL() The URL. createObjectURL() static method creates a string containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
The readAsDataURL method is used to read the contents of the specified Blob or File . When the read operation is finished, the readyState becomes DONE , and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.
You cannot create a File object only giving an URL to it.
The right method is to get the file through a Http request and read it, with something like this:
var blob = null
var xhr = new XMLHttpRequest()
xhr.open("GET", "path/to/file")
xhr.responseType = "blob"
xhr.onload = function()
{
blob = xhr.response
LoadAndDisplayFile(blob)
}
xhr.send()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With