15

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?

Adrian Taylor
  • 544
  • 1
  • 5
  • 14

2 Answers2

12

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()
Mijamo
  • 3,436
  • 1
  • 21
  • 21
  • 3
    Thanks for your answer. In order to make your solution work I just had to create a new File object from the blob using: new File([blob], blob), then LoadAndDisplayFile(file) – Adrian Taylor Feb 06 '16 at 09:12
  • Alright, I though the creation of the File object happened inside the LoadAndDisplayFile function. – Mijamo Feb 06 '16 at 12:59
0

I was dealing with same error and after spending time I created new File object using below code

                              new File(
                                [""],this.name,{
                                lastModified: 1605685839310,
                                lastModifiedDate: new Date(),
                                size: this.size,
                                type: "",
                                webkitRelativePath: ""
                            });
Nida Akram
  • 332
  • 2
  • 9
  • 24