最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript creating a file from URL - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Feb 5, 2016 at 8:58 Adrian TaylorAdrian Taylor 5541 gold badge5 silver badges15 bronze badges 3
  • Depends on what the "3rd party" script does? – Liam 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 – Marcos Pérez Gude Commented Feb 5, 2016 at 9:08
  • stackoverflow.com/questions/8390855/… – Blag Commented Feb 5, 2016 at 9:12
Add a comment  | 

2 Answers 2

Reset to default 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()

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: ""
                            });
发布评论

评论列表(0)

  1. 暂无评论