Solved

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

Posted on 2010-09-11
3
1,896 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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

747 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

12 Experts available now in Live!

Get 1:1 Help Now