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?

3
  • Depends on what the "3rd party" script does? Commented Feb 5, 2016 at 9:00
  • 2
    Uncaught TypeError: Failed to construct 'File': 2 arguments required, but only 1 present. Well, so pass 2 arguments, not one Commented Feb 5, 2016 at 9:08
  • stackoverflow.com/questions/8390855/… Commented Feb 5, 2016 at 9:12

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

2 Comments

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)
Alright, I though the creation of the File object happened inside the LoadAndDisplayFile function.
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: ""
                            });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.