Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript creating a file from URL

Tags:

javascript

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?

like image 247
Adrian Taylor Avatar asked Feb 05 '16 08:02

Adrian Taylor


People also ask

Can JavaScript create a File?

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.

What is URL createObjectURL in JavaScript?

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.

What is readAsDataURL?

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.


1 Answers

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()
like image 181
Mijamo Avatar answered Oct 13 '22 18:10

Mijamo