Home > Mobile >  How to check the file is already uploaded or not by using Ajax File Upload?
How to check the file is already uploaded or not by using Ajax File Upload?

Time:01-05

I am asking a question about Ajax File Upload again.. T_T

I have an ASP.NET webform (using VB.NET) which is using Ajax File Upload. I update my database table whenever I upload a file. I am checking a file is already uploaded or not when I drag into my upload panel and click the upload button. If the target file is already uploaded, I want to show my error label like 'the file is already uploaded' . But the label doesn't showing . I did debug to trace the result and the file is really existing and it went through my label text setting but didn't show on my form. Which part of my code is being wrong? I hope someone can guide me.

here is my asp code

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
 <script type="text/javascript">
  //customize the drag panel
  function AjaxFileUpload_change_text() {           
             Sys.Extended.UI.Resources.AjaxFileUpload_Upload = "Click Upload";
             document.getElementsByClassName('ajax__fileupload_uploadbutton')[0].style.width = '100px';             
         }
</script>
    <div style="width:40%;padding:25px;margin-left:200px">
        <asp:ScriptManager runat="server"></asp:ScriptManager>
        <ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" 
            OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384" AllowedFileTypes="pdf" MaximumNumberOfFiles="10" />
            <asp:Button ID="cmdDone" runat="server" Text="Done" style="display:none" ClientIDMode="Static" />
            <script>
                function MyCompleteAll() {
                    $('cmdDone').click()                    
                }
            </script>        
    </div>
    <asp:Label ID="lblmsg" runat="server" Text="" Width ="150px" style="color:red"></asp:Label><br />
</asp:Content>

.vb code

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 ClientScript.RegisterStartupScript(Page.GetType(), "OnLoad", "AjaxFileUpload_change_text();", True)  //customize ajax panel
 lblmsg.Text = ""  //error display
End Sub

Protected Sub MyCompleteAll(sender As Object, e As AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
 Dim filename As String = e.FileName.Split(".").First   "_"   fileupload   ".pdf"
 Dim path As String = Server.MapPath("~/uploads/")
 //to add a database table of files up-loaded.
 Dim constr As String = CONN   g_schema
  Using con As New MySqlConnection(constr)
   con.Open()
   'check file is already uploaded
   Dim select_seq As String = "select fname from filetable where fname like '"   
   e.FileName.Split(".").First   "%'"
   Dim cmd As New MySqlCommand(select_seq, con)
   Dim reader = cmd.ExecuteReader()
   While reader.Read()
    fname = reader(0).ToString
   End While
   con.Close()
   //the file is already uploaded
   If fname IsNot "" Then
    lblmsg.Text = "Already uploaded. Please upload the other files."
   Else
     // Upload process code 
End Sub

Thank you.

CodePudding user response:

I going to suggest you check the file on the file upload done event.

So, we can THEN build up a list of files that exist - you have the possibility of more then one file up-load.

So, I suggest dropping in a text box to "hold" each bad (duplicate) file.

So, lets persist into session() the duplicate files (we can NOT use controls on the page in the 3 events (start, complete, complete all).

So, we have this code:

Dim DupList As New List(Of String)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then
        Session("DupList") = DupList
        txtDups.Visible = False
    Else
        DupList = Session("DupList")
    End If

End Sub

And say this markup - the text box, a grid view, and of course the FileUpload.

So, say this markup up:

        <div style="width:40%;padding:25px">
        <ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" 
            OnClientUploadCompleteAll="MyCompleteAll"  ChunkSize="16384"                
            />

            <asp:Button ID="cmdDone" runat="server" Text="Done"
                style="display:none" ClientIDMode="Static"/>

            <asp:TextBox ID="txtDups" runat="server" TextMode="MultiLine" Width="523px"></asp:TextBox>


            <script>
                function MyCompleteAll() {
                    $('#cmdDone').click()
                  }
            </script>
            <asp:GridView ID="Gfiles" runat="server" CssClass="table" DataKeyNames="ID"></asp:GridView>
        </div>

So far - VERY good you have that JavaScript button click to get our VERY imporant and needed final post back when done.

So, a single file upload done event - looks like this:

Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete


    ' now code to add say to a database table of files up-loaded.
    ' but FIRST CHECK if the file already exists

    Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = @F"
    Dim cmdSQL As New SqlCommand(strSQL)
    cmdSQL.Parameters.Add("@F", SqlDbType.NVarChar).Value = e.FileName

    Dim rstFiles As DataTable = MyRstP(cmdSQL)

    If rstFiles.Rows.Count > 0 Then
        ' the file exists - don't save, add to our already exist list
        DupList.Add(e.FileName)
        Session("DupList") = DupList
    Else
        ' file is ok, new - save it
        Dim strFileSave As String
        strFileSave = Server.MapPath("~/Content/" & e.FileName)
        AjaxFileUpload1.SaveAs(strFileSave)

        ' now add to database
        Dim NewRow As DataRow = rstFiles.NewRow
        NewRow("FileName") = e.FileName
        NewRow("UpLoadTime") = Date.Now
        NewRow("User_id") = 1
        NewRow("Size") = e.FileSize
        NewRow("SavePath") = Path.GetDirectoryName(strFileSave) ' get path only
        rstFiles.Rows.Add(NewRow)
        MyRstUpdate(rstFiles, "MyUpLoadFiles")

    End If

End Sub

So note in above HOW WE SKIP the file if it exists. And of course if it does exist, then we of course don't make an entry in the MyFilesUpLoad table.

Ok, so all files up-load - that js button click fires, and we now have this final code stub run:

Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click

    ' this final code is triggered by the javascrpt "click" on 
    ' all file uplaod done

    ' if there are some duplicates - dispay to user.
    If DupList.Count > 0 Then
        txtDups.Visible = True
        For Each s As String In DupList
            If txtDups.Text <> "" Then txtDups.Text &= vbCrLf
            txtDups.Text &= s & " already exists - skipped and not uploaded"
        Next
    End If

    ' now addtonal code - maybe display gird of up-loaded files
    Dim strSQL As String = "select * from MyUpLoadFiles where UpLoadTime >= @D"
    Dim cmdSQL As New SqlCommand(strSQL)
    cmdSQL.Parameters.Add("@D", SqlDbType.DateTime).Value = Date.Today

    Gfiles.DataSource = MyRstP(cmdSQL)
    Gfiles.DataBind()
    ' hide up-loader
    AjaxFileUpload1.Visible = False

End Sub

So, it will look like this:

enter image description here

We hit ok, and now we have/see this:

enter image description here

Ok, so now lets try to re-upload two files that exist.

We So, we will see this:

enter image description here

So, we persist that "bad" list, and skip/don't save the file in the complete event.

And here are the two data helper routines - I don't think it needs much suggesting that one gets VERY tired VERY fast by having to type over and over some simple code to get data into a table - so I used these two helper routines to save World poverty and a few keyboards

Public Function MyRstP(cmdSQL As SqlCommand) As DataTable

    Dim rstData As New DataTable
    Using cmdSQL
        Using conn = New SqlConnection(My.Settings.TEST4)
            cmdSQL.Connection = conn
            conn.Open()
            rstData.Load(cmdSQL.ExecuteReader)
        End Using
    End Using

    Return rstData

End Function

Public Sub MyRstUpdate(rst As DataTable, strTable As String)

    Using conn As New SqlConnection(My.Settings.TEST4)
        Using cmdSQL As New SqlCommand("SELECT * from " & strTable, conn)
            Dim da As New SqlDataAdapter(cmdSQL)
            Dim daU As New SqlCommandBuilder(da)
            conn.Open()
            da.Update(rst)
        End Using
    End Using

End Sub

Edit: Check for "confirmed" file

Follow up question was not only does the file exist, but at some point (or some how - not yet disclosed), the use has the means to check box, or change the status of the up-loaded files. And if file has not yet been confirmed, then we still allow up-loading.

So, the code in question would be this:

Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = @F
    AND Confirmed = 9"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("@F", SqlDbType.NVarChar).Value = e.FileName

Dim rstFiles As DataTable = MyRstP(cmdSQL)

If rstFiles.Rows.Count > 0 Then ' the file exists. ' file is confirmed - don't save, add to our already exist list DupList.Add(e.FileName) Session("DupList") = DupList Else ' file is ok, new - save it - (or not confirmed)

  •  Tags:  
  • Related