Using the Htmlinput File Control

The HtmlinputFile control has been designed to program against the HTML <input type=file> element.We can use this control to enable users to upload binary or text files from a browser to a directory that we specify in our Web server. Its major attributes are as follows:

<input type=file runat="server" id="programmaticID" accept="MIMEencodings" maxlength="maxfilepathlength" size="widthoffilepathtextbox" postedfile="uploadedfile"

When this control is rendered, it automatically displays a Browse button for directory browsing. Figure 3.34 illustrates the usage of an HtmlinputFile control. The user may upload a file from his or her machine to our c:\temp directory of the Web server.The code for this application is shown in Figure 3.35 and is available on the CD in a file named HtmlFile1.aspx. As you will observe from this code, we have used the fileControl.PostedFile.SaveAs(("c:\temp\" + targetName.Value)) statement to accomplish the objective.

Figure 3.34 Using the HtmlFile Control for Uploading Files to the Server

Figure 3.34 Using the HtmlFile Control for Uploading Files to the Server

Figure 3.35 HtmlFile1.aspx

<!— HtmlFile1.aspx —><html><head></head> <h3>Using Html File Control</h3>

<form enctype="multipart/form-data" runat="server"> Select a file to upload:

<input type="file" id="fileControl" runat="server"><br> Save as: (Just the name only please):

<input id="txtTargetName" type="text" runat="server"><br> <input type=button id="btnLoad" value="Upload"

OnServerClick="btnLoad_Click" runat="server"><br> <span id=span1 runat="server" /><br> </form></html>

<script language="VB" runat="server"> Sub btnLoad_Click(s As Object, e As EventArgs) If txtTargetName.Value="" Then span1.InnerHtml="Error: you must enter a file name" Return End If

If Not (fileControl.PostedFile Is Nothing) Then Try fileControl.PostedFile.SaveAs(("c:\temp\" + targetName.Value)) span1.InnerHtml="Done: File loaded to <b>c:\temp\" + _ txtTargetName.Value & "</b> on the Web server" Catch err As Exception span1.InnerHtml="Error saving file <b>c:\temp\" + _

txtTargetName.Value & "</b><br>" & err.ToString() End Try End If End Sub </script>

0 0

Post a comment