Summary:
To check if a file has already been uploaded using Ajax, you can create an HTML form with a file input and use JavaScript with jQuery to send an Ajax request to a server-side script. In the server-side script (PHP in this example), check if the file exists in the designated upload directory. The server then responds with a message indicating whether the file exists or not, and this message is displayed on the HTML page.
Solution
Here is the generic code to get started:
HTML with Ajax file upload form:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Upload</title> <!-- Include jQuery --> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> </head> <body> <form id="fileUploadForm" enctype="multipart/form-data"> <input type="file" name="file" id="fileInput"> <button type="button" onclick="checkFile()">Check File</button> </form> <div id="status"></div> <script> function checkFile() { var fileInput = document.getElementById('fileInput'); var file = fileInput.files[0]; var formData = new FormData(); formData.append('file', file); $.ajax({ type: 'POST', url: 'check_file.php', // Replace with your server-side script for checking file existence data: formData, contentType: false, processData: false, success: function(response) { // Handle the response from the server $('#status').html(response); } }); } </script> </body> </html> |
PHP (check_file.php) on the server side:
<?php $uploadDirectory = 'uploads/'; $uploadedFile = $uploadDirectory . basename($_FILES['file']['name']); $fileExists = file_exists($uploadedFile); if ($fileExists) { echo 'File already exists!'; } else { echo 'File does not exist.'; } ?> |
Solution:
Now let’s start with the actual code:
Let us persist the duplicate files into the session() since we are unable to use controls on the page for the three events (start, complete, and complete all).
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 |
This markup includes the text box, a grid view, and of course the FileUpload. Also included is the grid view.
To put this markup in perspective:
<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> |
We have made great progress with the JavaScript button you clicked to receive our crucial and urgent final post when it is complete.
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 |
Clicking the js button launches this final code stub once all files have uploaded:
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, the output will look like this:
Answered by: >Albert D. Kallal
Credit:> StackOverflow
Suggested blogs:
>How to insert new data into the table in Django?
>Disabling default ordering in the Django admin panel
>How to migrate `DateTimeField` to `DateField` in Django?
>Python code can be hosted in Heroku or not?
>Why VueJS / Vuetify error rendering a vTable component?
>How to watch for event changes on a tailwind listbox component with Vuejs?
>How to add the total amount for each index list Vuejs?
>How to set up a dynamic grid based on flex or grid in Vuejs?
>How to get all the rows selected in Vuejs?