CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Peter's Gekko

public Blog MyNotepad : Imho { }

The proper way to open a file dialog from your webpage

Yesterday I blogged on the way to start a fileopen dialog from a web-page. Thanks to the feedback we discovered there's a very bad turn to that solution, the ActiveX control used only works on a machine which has MS devtools installed. Which is your or my machine but not that of the customer who is going to use the application. On the web I found a new solution which is pretty neat and doesn't need any ActiveX at all.

In HTML there's the INPUT control of type file. It is an input box which automatically gets a button. Clicking this button will start the desired file-open dialog, completing that copies the filename into the textbox. Using the example found on the web I have crafted the following solution.

  • Create a hidden input file control
  • Create a script function which fires the click of the file-input control and copies the selected value into an asp.net textbox
  • Add an onclick handler to a button to fire this script function.

This is the script snippet on the page

<SCRIPT language=JavaScript> function BrowseClick(){
document.forms[0]['fileBrowse'].click();
document.forms[0]['TextBox1'].value = document.forms[0]['fileBrowse'].value;
return false;}
</SCRIPT>

Which is a stripped version of the example found. Again I assemble the script from code

const string fiName = "fileBrowse";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<div style='visibility: hidden; width: 0px; height: 0px'>");
sb.Append(string.Format("<input type=file id='{0}'></div>", fiName));
sb.Append("<Script language=JavaScript> function BrowseClick(){");
sb.Append(String.Format("document.forms[0]['{0}'].click();", fiName));
sb.Append(String.Format("document.forms[0]['{0}'].value = document.forms[0]['{1}'].value;", TextBox1.ClientID, fiName));
sb.Append("return false;} </Script>");
 

RegisterClientScriptBlock(scriptKey, sb.ToString());

ButtonLinkNaarDocumentatie.Attributes.Add("OnClick", "return BrowseClick();");

This also works on my wife's XP-home machine. Thanks a lot to Andrew, Micheal Harris and Botolph.

blog on,

Peter



Comments

Chris Cochran said:

Good work!

Been trying to find a solution for that particular problem. Thanks for sharing it.
# January 27, 2004 8:17 PM

HP said:

Thanks a lot!
# August 9, 2004 8:51 AM

sk said:

excellent work done
thanks for the help that u have extended to the developers
# October 30, 2004 2:40 AM

sk said:

how to add filters to the file open dialog box?
# October 30, 2004 2:51 AM

sk said:

how to add type filters to the open dialog box?
# October 30, 2004 2:52 AM

Peter van Ooijen said:

Copied this from the w3c site.

File Attachments (type=file)

This allows users to attach one or more files to be submitted with the form's contents. The ACCEPT attribute can be used to specify a comma separated list of MIME content types. These are used to restrict the kinds of files that can be attached to the form. For instance:

<input name=pictures type=file accept="image/*">

This example restricts files to match "image/*", i.e. to registered MIME image types. For windows based user agents, it is suggested that file fields display the name of the last file attached, with the ability to open a file dialog box to view the complete list of files attached so far. The accept attribute then acts to specify the filter on the list of candidate files.

Does that help ?
# November 2, 2004 3:03 AM

Martin said:

Thanks, that's great. Is there a way to make it open a Save dialog?
# November 3, 2004 6:45 PM

Peter van Ooijen said:

I'm not sure what you are looking for. Isn't that the standard dwonload/save as dialog ? Or do you want to set the filename under which the file wil be saved on the server ? Will make the dialog complicated, a local and a remote filename.
# November 8, 2004 1:29 AM

Nick said:

Is it possible to put a defaut filter for file type, like *.txt
# November 10, 2004 1:13 PM

Peter van Ooijen said:

You mean add a filter to the dialog box itself ? Afaik that's beyond the possibilities ... It's not part of the specs.
# November 11, 2004 2:17 AM

vinay said:

where did u learn javascript from?
# December 2, 2004 3:17 AM

anil said:

hey, stupid and idiotic code.peter first learn properly and then start giving sample code to others
# December 2, 2004 3:19 AM

Peter van Ooijen said:

hey mr. anonymous : would you be so kind to say _what you consider_ wrong ? imho there's nothing wrong with the sample.


# December 2, 2004 3:56 AM

swathi said:

please send th answer for the requested
# January 21, 2005 11:35 PM

Peter van Ooijen said:

What is the question?
# January 22, 2005 3:43 AM

jdw said:

Not sure what anonymous is talking about. It works great. Thanks!!!
# July 28, 2005 3:44 PM

Daniel Goodhew said:

Peter excellent mate. Oi anonymous get your head out of your ***.
Been Googling for Comdlg examples but they are all as i thought... more problems than the problems that they fix.
Thanks for the neat trick
# September 19, 2005 3:52 AM

aroon said:

I'm trying to implement this in my ASP.NET form and its not working. What I am experiencing is that in the BrowseClick function the click() function fires but doesnt block the javascript execution so the rest of the function completes before any value for the fileBrowse element is even set...

is there an onValueChange event or something like that for the <input type=file> element? I'm searching for one now...
# March 2, 2006 12:45 PM

aroon said:

i figured it out! instead of binding your javascript function to the onClick event, bind it to the onpropertychange event. in your javascript function all you need to do is copy the value from the file input element to your asp element and you're done. no need to launch the click() function.
# March 2, 2006 12:56 PM

wally75 said:

Hi to All,
I tried to do this, but I've a trouble...
Only for test pourpose, I left file control visible, so I've seen that if I click on my new Browse button, after common dialog appears and both textboxes are filled with filename, when I click Send button, file control reset itself (but filename still remain in my new textbox), and ONLY the 2nd click will be handled by code behind (with several errors due to the reset of file control). If I click to the browse button of the file control, instead, it works fine! Why???
Thanks all!
# April 6, 2006 10:10 AM

pvanooijen said:

The opendialog is handeled on the client. The code behind is executed on the server and will not happen before the browser posts back to the server. With the post-data of the secend click.
# April 7, 2006 2:53 AM

sk said:

Good Idea!!!Thanks a lot!It saved me to re-invent the wheel!!!
# April 25, 2006 10:26 AM

Peter Chen said:

Great work! Thank you for sharing it. This is actually what I am looking for.
# April 26, 2006 8:22 PM

mitch said:

I know the answer is probably "no" but I have to ask: Is there anything like this for a Save As ... dialog?
# May 15, 2006 3:27 PM

pvanooijen said:

Mitch, it's not in the w3c specs... Perhaps with some fiddliing ? The main problem is to make it accept the name of a non-existing file.

# May 18, 2006 3:53 AM

bozo said:

@mitch:
in the code example, instead of "cdl.showopen;" you should write "cdl.showsave;"

One more tip if you experience difficulties creating the object "MSComDlg.CommonDialog":just register "ComDlg32.ocx" using following line (use path if neccessary!):
regsvr32 comdlg32.ocx

hope it will work for all of you, too.
# June 14, 2006 7:29 AM

pvanooijen said:

eh bozo, this post is about creating a dialog _without_ using a (com wrapper around) common dialog, but using an html input control instead. The com one was the bad idea, because most user don't have this installed. Even if they could their hands on it they often don't have the necessary rights to register the control.
# June 15, 2006 4:12 PM

Moua Golmiri said:

ii isnt good enough
# July 23, 2006 4:29 PM

Master said:

by using this code, i can get the file path eg "c:\xxx\text.txt", it works fine if i am using my local site. But when i access server site then at that time it try to read from the same path from the server ie "c:\xxx\text.txt", but file is not on the sever, it is on my local pc. so how to upload file from local pc to the sever using this???

# September 27, 2006 1:27 AM

pvanooijen said:

The dialog looks for a file on the machine your browser is running on. You cannot access the filesystem on the server. Or am I misunderstanding you ?

# September 28, 2006 3:07 AM

wozza said:

this is great. I just want to get a file name from the user, the file name will be stored in the database. I don't the actual file uploaded. this does the job, after I followed plenty of red herrings.

mitch: if you want save as, try

document.execCommand("saveAs")

# June 20, 2007 1:20 AM

apondu said:

Hi,

Nice article, but i feel it does not work in Mozilla or any other browsers other than Internet Explorer, can anyone let me know the reason and how to solve this or am i missing something, it would be great if someone responds back with a suggestion or  answer

My mail-id is apondu@gmail.com

# September 16, 2007 3:17 PM

pvanooijen said:

It should work in every browser as it is standard html. :?

# September 25, 2007 4:02 PM

Thiruvengadam said:

document.forms[0]['fileBrowse'].click();

This code is working in IE but not in Mozilla Firefox.

# October 17, 2007 2:37 AM

that dude from high school said:

I think I'm just going to use a custom (I beleive the term is submodal) dialog for my text editing webapp. Nice tut, though ;) . My only problem would be to retrieve the directories.

I know this is a bit off-topic, but does anyone have any ideas?

# November 18, 2007 12:31 AM

Windows Vista Blog said:

Thank you very much man...

# April 23, 2008 5:01 AM

Bernie said:

I am attempting to implement something like JavaScript that is described here.  My goal is to popup the File Selection dialog without the end-user having to first click the Browse button, and then to bring the contents of the user-selected file back to the web server.  However, when the associated form gets submitted, an “Access is denied” error always results.  I am using Internet Explorer 6 and suspect that I am encountering some sort of security issue with respect to the behavior of JavaScript's file-type input control.  I would appreciate any thoughts or suggestions on this.

I also have a couple of questions about the JavaScript in your implementation of the BrowseClick() function.  What is the purpose of assigning the value of the fileBrowse file-type input to TextBox1?  Also, why is it necessary that the BrowseClick() function return false?

Thanks,

Bernie

# June 25, 2008 6:18 PM

pvanooijen said:

I'm blank on the security issue.

The filename is assign to a text box to have it available for an edit-by-hand.

The script returns false to prevent a postback.

# June 30, 2008 11:23 AM

Bernie said:

Hi Peter,

Thanks for your reply.

If the purpose of having 'TextBox1' on the page is to be able to edit the full-path file name by hand, then why do you have the div around 'fileBrowse' (the file-type input).  That div hides 'fileBrowse' and its edit box?  I must be misunderstanding something you are trying to do here.  Couldn't you have instead simply eliminated 'TextBox1' entirely and shown 'fileBrowse'?  Wouldn't that have provided the end-user with precisely the same functionality?

Bernie

# July 3, 2008 2:49 AM

pvanooijen said:

ehh, perhaps.. Have to dive back into that specific project to find out...

You're free to try what works for yourself

# July 3, 2008 4:50 AM

Bernie said:

It would be great if you could take a deeper look at this.

Here is a sample of the JavaScript that I am working with that has been modified to use your web server for its submit:

<html>

<head>

<script type = 'text/javascript'>

function selectFile()

{

   document.forms[0]['#ICOrigFileName'].click();

}

function submitAction_win0(form, name)

{

form.ICAction.value=name;

form.submit();

}

</script>

</head>

<body onload="selectFile()">

<form name='win0' method='post' action="http://codebetter.com/"  autocomplete='off' enctype='multipart/form-data'>

<input type='hidden' name='ICAction' value='None' />

<input type='file' name='#ICOrigFileName' size='50' />

<input type='button' class='PSPUSHBUTTON' value='Upload' name='Upload' onclick="submitAction_win0(this.form,'#ICOK');" PSaccesskey='\' />

<input type='button' class='PSPUSHBUTTON' value='Cancel' onclick="submitAction_win0(this.form,'#ICCancel');" />

</form>

</body>

</html>

If you run this code (double-click on a file containing it in Windows Explorer) with IE6 and JavaScript debugging turned on, it will automatically prompt you for a file to upload.  But if you then select a file and manually click the Upload button on the page, you will get an "Access is denied" error message.

However, if you simply remove the onload statement (and the function call it specifies), then run the resulting code, you will need to manually click the Browse button to select a file (which is expected), but then manually clicking the Upload button works fine (it does the submit, takes you to the corresponding website, and produces no error message).

Bernie

# July 3, 2008 9:18 AM

pvanooijen said:

Bernie, that's beyond my scope at this moment. Tomorrow morning I'm leaving for a holiday.

Perhaps someone else over here ?

# July 3, 2008 11:10 AM

Calvin said:

This does not work in firefox..any work around/alternative?

# July 9, 2008 1:08 PM

Galina Toms said:

Please look at <br /> www.ardentedge.com/pr_WidgetBuilder_FileDialog.htm <br />.

You can find solution for all browsers.

# July 9, 2008 7:04 PM

Bernie said:

With the same code, the behavior is different on FireFox.  If run the same code on FireFox, the file selection dialog does not automatically open.

Bernie

# July 10, 2008 9:52 PM

Chtopor said:

Sorry,  but this code not supported in Opera!

# July 17, 2008 2:27 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Check out Devlicio.us!

This Blog

Syndication

News