Results 1 to 3 of 3

Thread: Anything better than AsyncFileUpload or AjaxFileUpload

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Feb 2002
    Location
    Canada, Toronto
    Posts
    5,802

    Anything better than AsyncFileUpload or AjaxFileUpload

    I am making a webapp for work that lists some projects in a Repeater, and for each project the user has to attach some files. So each control is repeated multiple times on the page.

    I can't use AjaxFileUpload because I don't know the file attached from which of the controls (project) is coming from.

    I don't like AsyncFileUpload because it refreshes the whole page, but this is what I am using right now, because it works...


    I need a control that can be placed multiple times on the page (like inside a repeater), and also upload file(s) without refreshing the entire page. Anything reliable?

  2. #2
    King of sapila
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    6,597

    Re: Anything better than AsyncFileUpload or AjaxFileUpload

    I think you're kinda stuck with traditional ASP.NET and server controls.
    The alternative would be to use JS and Templates but I'm not going to lie, seeing a project I made back in 2013 , yeah, it's rough.
    However if you have knowledge of JS, Jquery and html then you may be able to use Jquery pagination and put a template to be repeated.
    The template will probably be something like:

    Code:
     <table>  
            <thead>  
                <th>Project</th>            
            </thead>       
                <tr>              
                    <td>file attacher</td>                 
                </tr>        
        </table>

    Or you can go with Angular or any other news JS Framework.

    Since 2015 was probably the last time I used asp.net I can't provide deeper knowledge if you want to go JS way (it will come back to me if I restart but, no time) i think szlamany is a heavy worker on these kinda stuff.

    To specify what I mean by saying JS, html ,Jquery
    This project I made back in 2013 was on JS , Jquery, html and mustache and repeated news but it's your typical more than 1000 lines of JS and HTML code to get it working the template and it looks like like this:

    (fingers crossed for working picture...)

    Attachment 181047
    ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
    πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·

  3. #3
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Anything better than AsyncFileUpload or AjaxFileUpload

    I used IFRAME's in the past to do uploads that did not refresh the page. This method started failing in Chrome. I recently enhanced it to do an AJAX POST with FormData() to do the upload.

    JS function looks like this - using jQuery

    Code:
    function uploadClick(event) {
        var wesSender = $(event.target);
        var strId = ""
        var wesDD = [];
        var strUPS = "";
        var wesUPE = [];
        var fd = new FormData();
        var wesFI = [];
        var file = {};
        if (g_blnInSproc) {
            alert("Processing - please wait!");
        } else {
            g_blnInSproc = true;
            wesDD = wesSender.closest(".acs-ddreflector");
            strId = wesDD.attr("id");
    
            wesFI = wesSender.siblings().find("input:file");
            file = wesFI.prop("files")[0];
            fd.append('file', file);
    
            strUPS = wesSender.attr("value") || "";
            strUPS = (window.username || "") + strUPS;
            wesUPE = wesDD.find('.acs-upload-switch');
            if (wesUPE.length != 0) {
                strUPS += "/" + wesUPE.text();
            }
            fd.append('username', strUPS);
            $.ajax({
                url: 'upload.ashx',
                type: 'post',
                data: fd,
                contentType: false,
                processData: false,
                success: function (response) {
                    uploadComplete("#" + strId, response);
                },
                failure: function (response) {
                    alert("Upload failure");
                },
                error: function (response) {
                    alert("Upload error");
                }
            });
        }
    }
    This is the UploadComplete() function.

    Code:
    function uploadComplete(strId, strResult) {
        var returnObj = {};
        var updArr = [];
        var strData = "";
        var wesAWC = [];
        var wesClone = [];
        var wesDD = $(strId);
        var strEditKey = wesDD.data("objWebParam").editkey;
        var strUpdKey = "";
        var updkeys = [];
        g_blnInSproc = false;
        $($.find(".acs-upload-spinner")).remove();
        returnObj = $.parseJSON(strResult);
        updArr = returnObj.update || [];
        for (var i = 0; i < updArr.length; i = i + 2) {
            strData = updArr[i + 1];
            wesAWC = $(strId + " .awc-" + updArr[i]).not(".acs-edit-view-hidden");
            p_fillField(wesAWC, strData, strId, updArr[i], false, false, false, updArr);
            if (strEditKey.length != 0) {
                if (strEditKey == updArr[i]) {
                    strUpdKey = strData;
                }
            }
        }
        if (strUpdKey.length != 0) {
            if (typeof wesDD.data('updkeys') == "undefined") {
                wesDD.data('updkeys', []);
            }
            if ((strUpdKey != undefined) && (strUpdKey.length != 0)) {
                updkeys = wesDD.data('updkeys');
                updkeys.push(strUpdKey);
                wesDD.data('updkeys', updkeys);
            }
        }
        if (returnObj.ok) {
            $(strId).find("input[type=file]").val("");
            errorMessage("Upload Complete", returnObj.message);
        } else {
            errorMessage("Upload DID NOT Complete", returnObj.message);
        }
        return false;
    }
    I've also included UPLOAD.ASHX - it's a generic routine used by all my clients in many different ways - so it's got tons of code that will make zero sense to you, but you can follow the basics of how it's working for the FormData() that is passed and how it's grabbing the file and what not.

    Code:
    <%@ WebHandler Language="VB" Class="Upload" %>
    
    Imports System
    Imports System.Web
    Imports System.IO
    Imports System.Data
    Imports System.Data.SqlClient
    
    Public Class Upload : Implements IHttpHandler
    
        Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
            Dim username As String = context.Request.Params("username")
            Dim credDB As String = ""
            Dim overSproc As String = ""
            Dim doMulti As Boolean = False
            Dim uploadExtra As String = ""
            Dim doExtra As Boolean = False
    
            If username.StartsWith("[") Then
                doExtra = True
                Dim cp As Integer = username.IndexOf("]")
                uploadExtra = username.Substring(1, cp - 1)
                username = username.Substring(cp + 1)
            End If
    
            If username.EndsWith("/multi") Then
                doMulti = True
                username = username.Substring(0, username.Length - 6)
            End If
    
            If username.EndsWith(")") Then
                Dim cp As Integer = username.LastIndexOf("(")
                overSproc = username.Substring(cp + 1, username.Length - cp - 2)
                username = username.Substring(0, cp)
            End If
            If username.Contains(":") Then
                credDB = username.Split(":"c)(0)
                username = username.Split(":"c)(1)
            End If
    
            Dim uploads As HttpFileCollection = context.Request.Files
    
            Dim gotError As Boolean = False
    
            If uploads.Count = 0 Then
                Dim strResp As String = "{""ok"": false, ""message"": ""No file presented for upload.""}"
                context.Response.Write(strResp) 'filename)
                context.Response.StatusCode = 200
                gotError = True
            Else
                If Not doMulti Then
                    If uploads.Count <> 1 Then
                        Dim strResp As String = "{""ok"": false, ""message"": ""Can only upload a single file at a time.""}"
                        context.Response.Write(strResp) 'filename)
                        context.Response.StatusCode = 200
                        gotError = True
                    End If
                End If
            End If
    
            Dim loopCount As Integer = 0
            If doMulti Then
                loopCount = 1
            End If
    
            If Not gotError Then
                Dim multiMessage As String = "'"
                Dim multiUpdate As String = ""
                For runLoop As Integer = 0 To loopCount
                    If gotError Then
                        Exit For
                    End If
                    For i As Integer = 0 To uploads.Count - 1
                        Dim postedFile As HttpPostedFile = uploads(i)
                        Dim didUpload As Boolean = False
                        Dim strResp As String = ""
                        Dim UpId As String = ""
                        Dim StoredFileName As String = ""
                        Dim Message As String = ""
                        Dim Update As String = ""
                        Dim MultiFlag As String = ""
                        If doMulti Then
                            MultiFlag = ""
                            If i = 0 Then
                                MultiFlag &= "F"
                            End If
                            If i = uploads.Count - 1 Then
                                MultiFlag &= "L"
                            End If
                            If runLoop = 0 Then
                                MultiFlag &= "*"
                            End If
                        End If
                        Try
                            Dim filename As String = postedFile.FileName
                            If filename = "" Then
                                strResp = "{""ok"": false, ""message"": ""No file presented for upload.""}"
                                context.Response.Write(strResp)
                                context.Response.StatusCode = 200
                                gotError = True
                                Exit For
                            Else
                                Try
                                    Using dcn As New SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings("LocalSQLServerAWC" & credDB).ToString)
                                        Using cmd As New SqlCommand
                                            cmd.CommandType = CommandType.StoredProcedure
                                            If overSproc <> "" Then
                                                cmd.CommandText = "dbo." & overSproc
                                            Else
                                                cmd.CommandText = "dbo.awc_UploadCreate"
                                            End If
                                            cmd.Connection = dcn
                                            cmd.CommandTimeout = 0
                                            cmd.Parameters.AddWithValue("@UploadFileName", filename)
                                            If doExtra Then
                                                cmd.Parameters.AddWithValue("@UploadExtra", uploadExtra)
                                            End If
                                            If doMulti Then
                                                cmd.Parameters.AddWithValue("@MultiFlag", MultiFlag)
                                            End If
                                            cmd.Parameters.AddWithValue("@username", username)
                                            dcn.Open()
                                            'UpKey = cmd.ExecuteScalar().ToString
                                            Using sdrReader As SqlDataReader = cmd.ExecuteReader
                                                While sdrReader.Read
                                                    If doMulti Then
                                                        If sdrReader.GetName(0) = "%%errormessage%%" Then
                                                            strResp = "{""ok"": false, ""message"": """ & sdrReader(0).ToString() & """"
                                                            strResp &= "}"
                                                            context.Response.Write(strResp)
                                                            context.Response.StatusCode = 200
                                                            gotError = True
                                                            Exit For
                                                        End If
                                                        If sdrReader.GetName(0) = "Status" AndAlso sdrReader(0).ToString() <> "success" Then
                                                            strResp = "{""ok"": false, ""message"": """ & sdrReader(0).ToString() & """"
                                                            strResp &= "}"
                                                            context.Response.Write(strResp)
                                                            context.Response.StatusCode = 200
                                                            gotError = True
                                                            Exit For
                                                        End If
                                                        If Not MultiFlag.EndsWith("*") Then
                                                            StoredFileName = sdrReader("StoredFileName").ToString()
                                                            didUpload = True
                                                            If MultiFlag.EndsWith("L") Then
                                                                Select Case uploads.Count
                                                                    Case 1
                                                                        multiMessage = "File successfully uploaded."
                                                                    Case Else
                                                                        multiMessage = uploads.Count.ToString() & " Files successfully uploaded."
                                                                End Select
                                                                multiUpdate = sdrReader("Update").ToString()
                                                            End If
                                                        End If
                                                    Else
                                                        If sdrReader.GetName(0) = "%%errormessage%%" Then
                                                            strResp = "{""ok"": false, ""message"": """ & sdrReader(0).ToString() & """"
                                                            strResp &= "}"
                                                            context.Response.Write(strResp)
                                                            context.Response.StatusCode = 200
                                                            gotError = True
                                                            Exit For
                                                        End If
                                                        UpId = sdrReader("AWCUploadId").ToString()
                                                        StoredFileName = sdrReader("StoredFileName").ToString()
                                                        didUpload = True
                                                        Message = sdrReader("Message").ToString()
                                                        Update = sdrReader("Update").ToString()
                                                    End If
                                                End While
                                            End Using
                                        End Using
                                    End Using
                                Catch ex As Exception
                                    LogOutput(ex.Message)
                                    strResp = "{""ok"": false, ""message"": ""awc_UploadCreate error.""}"
                                    context.Response.Write(strResp)
                                    context.Response.StatusCode = 200
                                    gotError = True
                                    Exit For
                                End Try
    
                                If didUpload Then
                                    Dim confSetting As String = "uploadfolder"
                                    Dim savepath As String = ""
    
                                    If StoredFileName.Contains("~~") Then
                                        Dim cp As Integer = StoredFileName.IndexOf("~~")
                                        confSetting = StoredFileName.Substring(0, cp)
                                        StoredFileName = StoredFileName.Substring(cp + 2)
                                    End If
    
                                    savepath = System.Configuration.ConfigurationManager.AppSettings(confSetting)
    
                                    If Not Directory.Exists(savepath) Then
                                        Directory.CreateDirectory(savepath)
                                    End If
    
                                    postedFile.SaveAs(Path.Combine(savepath, StoredFileName))
                                    If Not doMulti Then
                                        strResp &= "{ ""ok"": true"
                                        strResp &= ", ""message"": """ & Message & """"
                                        strResp &= ", ""update"": " & Update
                                        strResp &= "}"
                                        context.Response.Write(strResp) 'filename)
                                        context.Response.StatusCode = 200
                                    End If
                                End If
                            End If
                        Catch ex As Exception
                            LogOutput(ex.Message)
                            strResp = "{""ok"": false, ""message"": ""Error: " & ex.Message.Replace("""", "'").Replace("\", "\\").Replace(vbNewLine, "<br />") & ".""}"
                            context.Response.Write(strResp) 'filename)
                            context.Response.StatusCode = 200
                            gotError = True
                            Exit For
                        End Try
                    Next
                Next
                If Not gotError Then
                    If doMulti Then
                        Dim strResp As String = ""
                        strResp &= "{ ""ok"": true"
                        strResp &= ", ""message"": """ & multiMessage & """"
                        strResp &= ", ""update"": " & multiUpdate
                        strResp &= "}"
                        context.Response.Write(strResp) 'filename)
                        context.Response.StatusCode = 200
                    End If
                End If
            End If
        End Sub
    
        Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
            Get
                Return False
            End Get
        End Property
    
        Private Sub LogOutput(ByRef LogText As String)
            Dim strLogFile As String = "Upload_" & DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.CultureInfo.GetCultureInfo("en-US")) & ".log"
            Dim strLogFolder As String = System.Web.Configuration.WebConfigurationManager.AppSettings("logfolder")
            strLogFile = Path.Combine(strLogFolder, strLogFile)
            Using fs1 As FileStream = New FileStream(strLogFile, FileMode.Append, FileAccess.Write)
                Using s1 As StreamWriter = New StreamWriter(fs1)
                    s1.Write(DateTime.Now.ToString & ": " & LogText & vbCrLf)
                    's1.Write(LogText & vbCrLf)
                    s1.Close()
                    fs1.Close()
                End Using
            End Using
        End Sub
    
    End Class
    Last edited by szlamany; Apr 18th, 2021 at 05:20 AM.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width