Assigning a Value to AjaxFileUpload Control Using JavaScript or Code Behind

I have successfully implemented the AjaxFileUpload Control in my project.

Now, I am facing a challenge where I need to dynamically add a file to the AjaxFileUpload Control upon clicking a separate button. This will ensure that the FileUploadControl contains the selected file when the button is clicked.

My goal is to make sure that all events associated with the AjaxFileUpload Control also work seamlessly with this additional button.

Below is the code snippet for reference:


<cc1:AjaxFileUpload ID="AjaxFileUpload3" runat="server" AllowedFileTypes="zip" Enabled="true"
MaximumNumberOfFiles="1" OnUploadComplete="File_Upload"  OnClientUploadComplete="UploadCompleteArchive" 
Width="240px" /> 
                    <asp:UpdatePanel runat="server">
                        <ContentTemplate>
                            <asp:HiddenField ID="hfBoxZip_URL" runat="server" />
                            <asp:HiddenField ID="hfBoxZip_Name" runat="server" />
                            <asp:Button ID="btnZip" runat="server" Text="Button" OnClick="btnZip_Click" style="display:none;"/>
                        </ContentTemplate>
                    </asp:UpdatePanel>

I am seeking assistance either through JavaScript or CodeBehind (C#) to achieve this functionality.

Your help and guidance on this matter would be highly appreciated.

Answer №1

After exploring various options and experimenting, I have managed to come up with a somewhat effective solution.

Advantages of this solution:

- It enables users to upload a file and save it under any desired filename while displaying it on the screen.
- It is functional and works as intended.

Disadvantages of this solution:

- This solution seems to only work with AsyncFileUpload and not with AjaxFileUpload.
- There is a need to force a postback which results in a "screen flashing" effect, although it gets the job done.

The approach is simple. Instead of setting the image source directly in JavaScript, trigger an updatepanel postback. This assumes that you have already set the ImageURL in the code-behind.

Here is the complete code:

In the Head section of the ASP page:

<script type="text/javascript">
    function uploadComplete(sender, args) {
        __doPostBack('upTop', '');
    }
</script>

"upTop" refers to the ID of the UpdatePanel used.

The Body ASP code follows a standard structure:

  <asp:UpdatePanel ID="upTop" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Panel ID="Panel1" CssClass="panelbox" runat="server">
            <table>
                <tr>
                    <td>
                        <asp:Image ID="imgClient" runat="server" />
                    </td>
                    <td>
                        <ajaxToolkit:AsyncFileUpload ID="AsyncFileUpload1" OnClientUploadComplete="uploadComplete" OnUploadedComplete="AsyncFileUpload1_UploadedComplete" ThrobberID="MyThrobber" runat="server" />
                        <asp:Image ID="MyThrobber" ImageUrl="~/Images/pleasewait.gif" Style="display: None" runat="server" />
                    </td>
                </tr>
            </table>
        </asp:Panel>
    </ContentTemplate>
</asp:UpdatePanel>

Lastly, the code-behind section includes:

        Protected Sub AsyncFileUpload1_UploadedComplete(sender As Object, e As AjaxControlToolkit.AsyncFileUploadEventArgs)
        Dim Filepath As String
        Dim NewFileName As String

        Filepath = "/ClientPhotos"
        NewFileName = MapPath(Filepath) & "\" & CurrentCustomer.ID.ToString & ".jpg"
        Try
            AsyncFileUpload1.SaveAs(NewFileName)
        Catch ex As Exception
            ShowError("Error uploading photo: " & ex.Message)
            Exit Sub
        End Try

        Me.imgClient.ImageUrl = "~/ClientPhotos/" & CurrentCustomer.ID.ToString & ".jpg"
        Me.imgClient.Width = 200
        Me.imgClient.Height = 200

    End Sub

For more information, visit -

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for Updating Child Table with SQL QueryHere's how to update a child

Seeking assistance with updating 2 tables simultaneously by clicking a button. The two tables in question are WorkSchedule and WorkShiftBid. The objective is to update the WorkSchedule table by setting the "WorkScheduleStatus" column to "Pending," which ha ...

Error: Missing responseText in Jquery

Struggling with accessing ajax response data? I have encountered an issue with my ajax request that sends Json to a server and the response returns Json as well. Even though I receive the response, I am unable to access the responseText. Below is the code ...

Aggregate the array of objects into a new array and calculate the total sum of values

I have an array with the following structure, and I am attempting to separate objects into a new array by grouping two values. Array: [ { "year": "202003", "cost": 11194.55, "type": "A" }, ...

iScroll 4 experiencing issue with scrolling on input fields

I am currently in the process of developing a mobile application that is compatible with Android 2.2+, Blackberry 9+, and iOS 4+. Our technology stack includes Phonegap, jQuery, and iScroll (among other tools). One of the screens in our app resembles the ...

Strange behavior occurs when a DOCTYPE is specified in XSLT and javascript interactions

Within our XLST, we utilize "vanilla" JavaScript to manipulate certain div elements within our reports. One particular div sits in the center of the screen and overlaps all other content. The code snippet below is used to position this div when the page lo ...

Dragging and dropping Jquery accordion panels into a designated drop zone

Hello, I am currently working on incorporating a feature that resembles the MS Outlook accordion using jQuery. The desired functionality is such that when the accordion is minimized, the elements are placed in a designated area at the bottom, and when maxi ...

Ensure Website Accessibility by Implementing Minimum Resolution Requirements

Is it possible to create a website that only opens on screens with a resolution of at least 1024 x 768, and displays an error message on unsupported resolutions? I've tried using JavaScript to achieve this, but haven't had any success. Any assis ...

What is the Dojo counterpart for jQuery's .live() function?

Is there a Dojo alternative to jQuery .live() function? http://api.jquery.com/live/ In my search, the only workaround I came across was to disconnect the event handlers in Dojo and then reconnect them when new dynamic content is added to the page. ...

Manipulating date and time with C# for lengthy durations

Is there a way to combine a DateTime and a long value (representing hours) in C#? The desired outcome should be a DateTime object. ...

Node.js bypasses unit test validation

As a beginner in BDD with Node.js, I have a controller function defined as follows: var getUser = function(username, done) { console.log('prints'); User.findOne({ 'local.username': username }, function (err, user) { ...

Experiencing performance issues with multiple tweens in Three.js and Tween.js causing delays

Greetings to all, I am new to the world of Three.js and Tween.js and I have a question regarding the possibility of simultaneously tweening 200k vertices from one position to another using Three.js. Apologies in advance if I use the terms pixels and vertic ...

Guide to sending a POST request from within my application

I'm facing an issue with using $resource for making a post request in my app. Here is the code snippet from my Angular module: angular.module('myApp').factory('Product', ['$resource', function ($resource) { ...

Troubleshooting issue with Enum.GetValues method not functioning properly in T4 template

In the .tt template provided : <#@ template debug="true" hostspecific="true" language="C#" compilerOptions="/langversion:10" #> <#@ assembly name="System" #> <#@ assembly name=&qu ...

Implementing drag and drop functionality for dynamically generated components in Angular 7

I have a follow-up question based on my previous inquiry posted on Stack Overflow: Add directives to component selector when it is declared - Angular 7 My current scenario involves dynamically generating components upon clicking a button. These components ...

Tips for using useState with dependencies on custom objects such as { filter[], sort[] }:

I am trying to use the useState Hook with a custom object that contains two arrays as shown below const [initConfig, setInitConfig] = useState<>({filter:[], sort:[]}); However, I am unsure of how to declare inside the angle brackets. The filter arr ...

Using mapStateToProps to retrieve data

I have a component that requires data from my Redux store. However, the data is being passed in a different way than expected. I am unsure how to use mapStateToProps in this scenario to retrieve the necessary information. Here is the component where I nee ...

Guide to verifying the success of a payment using Stripe and ASP.NET

public ActionResult Index() { StripeConfiguration.ApiKey = "secretKey"; var options = new SessionCreateOptions { PaymentMethodTypes = new List<string> { "card", ...

Enhance Your Website with Interactive Tooltips Using Twitter Bootstrap

In Twitter bootstrap, the default trigger for tooltips is hover. If I want to make the tooltip display on focus instead, I can add data-trigger="focus". But how do I make it so the tooltip displays both on hover and on focus? ...

ngFor displaying items in a stacked layout within a flexible carousel

Incorporating Angular 11 along with the https://www.npmjs.com/package/angular-responsive-carousel responsive carousel has been a part of my project. The carousel is filled with mat-cards through an array. However, upon initially loading the page, all the c ...

Is it feasible to access an Exchange server in C# without using a domain name?

I am currently developing a web application to access an Exchange Server 2010 in order to retrieve emails from the server. My question is, we do not have a domain name for this server. All I have is its IP address. Is it possible to utilize Exchange Web Se ...