One step image load and display

Mark Klein
Mark Klein used Ask the Experts™
on
I am building an asp.net website in which a user picks an image from the user's file system and displays it on the site.  The code is presently working as a two step process:
1. Use FileUpload control to let the user select a file from local storage.  A Browse button is shown, and the user picks the file with the file name in the control
2. User clicks a Display button.  The file is checked and displayed so the user can add a description before uploading to db.

My client wants a one-step process, eliminating the Display button. I have unsuccessfully tried to implement this by triggering on the FileUpload events.  I've tried them all, w/o success. FileUpload only captures the file name.  How do I kick off my processing routines without another button click?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2014

Commented:
The form has to be posted back to the server for the file to be uploaded. This postback is usually done by button click.

To do what you want, you would need to use either Flash/silverlight or ActiveX.
Commented:
Can do this with a hidden button and a little javascript:

Here is the form:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="Image1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <asp:FileUpload ID="FileUpload1" runat="server" />
    </div>
    </form>
</body>
</html>

Open in new window


Here is the code behind:

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        FileUpload1.Attributes.Add("onchange", "document.getElementById('" & Button1.ClientID & "').click();")
        Button1.Attributes.Add("style", "display: none;")
    End Sub


    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        Dim path As String = Server.MapPath("UploadedImages/") + FileUpload1.PostedFile.FileName
        FileUpload1.SaveAs(path)
        Image1.ImageUrl = "UploadedImages/" & FileUpload1.PostedFile.FileName
    End Sub
End Class

Open in new window

Author

Commented:
Had to adjust the filepath slightly, adding "~/" and then it worked.  Thx

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial