Solved

Problem with partial-page refresh with AJAX AsyncFileUpload in VB.NET

Posted on 2010-09-11
3
1,902 Views
Last Modified: 2012-05-10
I am trying to use AJAX AsyncFileUpload to upload image files to the server. When the image file is uploaded, I want it to immediately appear on the page.

My image to refresh is called "frenchlogo". When the upload event fires, it calls a subroutine AsyncFileUpload2_UploadedComplete which checks and saves the file, and updates the source of the image (frenchlogo.ImageUrl).

The Asyncfileupload and image are in the same Updatepanel.

What am I doing wrong ?

Thanks, Peter
Protected Sub AsyncFileUpload2_UploadedComplete(ByVal sender As Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs)
If AsyncFileUpload2.HasFile then
    ' Determine new file name
    fileExtension = System.IO.Path.GetExtension(AsyncFileUpload2.Filename).ToLower()
    newfilename = "flogo-" & Session("sponsor") & fileExtension
    FolderToSave = Server.MapPath("\") & "Userdata\L-" & Trim(Session("Leaguenum")) & "\Advertisement\"

    ' Validate file is of correct type
    fileOK = False
    Dim allowedExtensions As String() = {".jpg", ".jpeg", ".png", ".gif"}
    For i As Integer = 0 To allowedExtensions.Length - 1
        If fileExtension = allowedExtensions(i) Then
            fileOK = True
        End If
    Next
        
    ' Save the file    
    If fileOK Then
        Try
            AsyncFileUpload2.PostedFile.SaveAs(trim(FolderToSave & newfilename))
            Outputmessage = "File uploaded!"
        Catch ex As Exception
            Outputmessage = "File could not be uploaded."
        End Try
    Else
        Outputmessage = "Cannot accept files of this type."
    End If

    ' Update database entry to indicate new banner name
        cmd.Connection = MyConn
        cmd.Connection.Open()     
        cmd.CommandText = "Update sponsors set sponsorlogofr = '" & newfilename & "' where sponsorid = " & Session("sponsor")
        cmd.ExecuteNonQuery()
        cmd.Connection.Close()

    ' Display the output message
    upload2Label.Text = Outputmessage

   End if

frenchlogo.ImageUrl = Foldertosave & newfilename
Showfrenchlogoimages.Visible = "true"

End Sub


<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Panel ID="Showfrenchlogoupload" runat="server">
            <tr>
                <td style="padding-left: 15px">
                    <ajaxToolkit:AsyncFileUpload runat="server" ID="AsyncFileUpload2" Width="400px"
	                    UploaderStyle="Modern" UploadingBackColor="#CCFFFF" ThrobberID="Throbber2"
	                    OnUploadedComplete="AsyncFileUpload2_UploadedComplete" />

                    <asp:Label runat="server" ID="Throbber2" Style="display: none;">
                        <img align="absmiddle" alt="" src="~/images/ajax-loader.gif" />
                    </asp:Label>
                    <br /><asp:Label id="upload2Label" runat="server" />
                </td>
            </tr>
        </asp:Panel>
        <asp:Panel ID="Showfrenchlogoimages" runat="server">
            <tr>
                <td align="center">
                    <asp:Image ID="frenchlogo" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Button4" Text="Change Logo" runat="server" OnCommand="ChangeAd"
                        CommandName="frenchlogo" />
                </td>
            </tr>
        </asp:Panel>
    </ContentTemplate>
</asp:UpdatePanel>

Open in new window

0
Comment
Question by:pbissegger
  • 2
3 Comments
 
LVL 5

Accepted Solution

by:
pschrama earned 500 total points
ID: 33656454
I managed to get it working by using OnClientUploadComplete and adding a javascript function that refreshes the updatepanel. Also, the image url is stored in session because OnUploadedComplete seems to call the page seperately without including viewstate. Hope this helps.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AsyncUpload.aspx.cs" Inherits="Experimentation.Pages.AsyncUpload" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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 runat="server">
    <title></title>
    <script type="text/javascript">
    function UpdatePanel1()
    {
        __doPostBack("UpdatePanel1", "");
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <div>
        <asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" OnUploadedComplete="AsyncFileUpload1_UploadedComplete" OnClientUploadComplete="UpdatePanel1" />
        
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Image ID="Image1" runat="server" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Experimentation.Pages
{
    public partial class AsyncUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Image1.ImageUrl = this.UploadedImageUrl;
            if (string.IsNullOrEmpty(this.UploadedImageUrl))
                Image1.Visible = false;
            else
                Image1.Visible = true;
        }

        public string UploadedImageUrl
        {
            get { return Session["uploadedImageUrl"] as string; }
            set { Session["uploadedImageUrl"] = value; }
        }

        protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            if (AsyncFileUpload1.HasFile)
            {
                string extension = System.IO.Path.GetExtension(AsyncFileUpload1.FileName);
                string[] validExtensions = new string[] { ".jpg", ".gif", ".jpeg", ".png" };
                if (validExtensions.Contains(extension))
                {
                    string savefileName = Server.MapPath("~/Pages/Images/" + AsyncFileUpload1.FileName);
                    AsyncFileUpload1.SaveAs(savefileName);
                    this.UploadedImageUrl = "~/Pages/Images/" + AsyncFileUpload1.FileName;
                }
            }
        }
    }
}

Open in new window

0
 

Author Comment

by:pbissegger
ID: 33678198
Thank you so much for your help. I am very impressed with the effort you put into this.

It took me a couple of days to figure out how to translate to VB, but it seems to be working now.

Thanks, Peter
0
 

Author Closing Comment

by:pbissegger
ID: 33678204
Excellent solution !
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now