Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

html - how to get files from <input type='file' .../> (Indirect) with javascript

I have problem with "input tag" in non IE browsers

<input type="file" ...

I'm trying to write my uploader , just using javascript and asp.net.

I have no problem uploading files.

My problem occured When I wanted to get my files in non IE browsers with

<input type="file" ...

I do not want to use directly from input because its appearance does not change correctly

I wrote this code to get files from hard disk :

function $tag(_str_tag) {
return document.getElementsByTagName(_str_tag);
}

function $create(_str_tag) {
    return document.createElement(_str_tag);
}


function $open_file() {
    _el_upload = $create("input");
    _el_body = $tag("body")[0];
    _el_upload.setAttribute("type", "file");
    _el_upload.style.visibility = "hidden";
    _el_upload.setAttribute("multiple", "multiple");
    _el_upload.setAttribute("position", "absolute");
    _el_body.appendChild(_el_upload);
    _el_upload.click();
    _el_body.removeChild(_el_upload);
    return _el_upload.files;
}

In IE it works pretty well and returns my files currently ; In Chrome And Firefox , After loading "file input dialog" , it can't return any file. And Opera and Safari are completely out.

I can fix it with this trick , but its not good basically.

_el_upload.click();
alert();

I think "callback" or "wait function" may fix this , but i can't handle it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are looking to style a file input element, look at open file dialog box in javascript. If you are looking to grab the files associated with a file input element, you must do something like this:

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

See this MDN article for more info on the FileList type.

Note that the code above will only work in browsers that support the File API. For IE9 and earlier, for example, you only have access to the file name. The input element has no files property in non-File API browsers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...