简体   繁体   中英

javascript creating a file from URL

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?

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()

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: ""
                            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM