Validating Multiupload file after uploaded and Return Success or Error

  1. #1

    Validating Multiupload file after uploaded and Return Success or Error

    I need to use multiupload component and add validation function OnFileUploaded.
    If the validation is true, than the uploaded file success.
    Else its error (even if upload is success, but if the validation is false than it show error).

    How can I do this?

    My current code is a copy to the example this.

    I try to change some code.

    I remove OnFileUpload event from <ext:MultiUpload> component.
    then on UploadComplete listener I set to my javascript handler completeRecord.
    <Listeners>
       <SwfUploadLoadFailed Fn="loadFailed" />
       <FileSelected Fn="fileSelected" />
       <UploadStart Handler="updateRecord(file.id, 'status', 'Sending');" />
       <UploadProgress Handler="updateRecord(file.id, 'progress', bytesComplete / bytesTotal);" />
       <UploadComplete Handler="completeRecord(file.id);" />
       <UploadAborted Handler="updateRecord(file.id, 'status', 'Aborted');" />
       <UploadRemoved Handler="var store = this.up('grid').store; store.remove(store.getById(file.id));" />
       <UploadError Fn="uploadError" />
       <FileSelectionError Fn="fileSelectionError" />
    </Listeners>
    this is my completeRecord
            var completeRecord = function (id, name) {
                updateRecord(id, 'progress', 1);
                updateRecord(id, 'status', 'Validating');
    
                if (CompanyX.ValidateFile(id) == true) {  //this is a Direct Method for validation
                    updateRecord(id, 'status', 'Success');
                } else {
                    updateRecord(id, 'status', 'Error');
                }
            };
    This is my direct method validation function (I'm using VB code but I can understand C# code if VB not supported).
        <DirectMethod>
        Public Function ValidateFile(id As Integer) As Boolean
            Try
                'Request.Files.Count = 0 HERE I don't know how to get Uploaded file here
                'Some Validation HERE
    
                ValidateFile = True
            Catch ex As Exception
                Ext.Net.X.Msg.Alert("Error", ex.Message).Show()
                ValidateFile = False
            End Try
        End Function
    My problem is I can't get the uploaded data using Request.Files from the direct method called.
    Anyone can help me to solve this? Maybe I'm missing something or any other suggestion is welcome.
    Last edited by Kuro13; Dec 14, 2016 at 10:46 AM.
  2. #2
    Hello @Kuro13, and welcome to Ext.NET Forums!

    Well, I believe in the direct event you are calling, the way you are calling has nothing to do anymore with the actual file upload, so you probably need to pass the file name (and maybe an user ID or session identifier) to know which file has been just uploaded.

    It would be very very slow if you re-uploaded the file again during the validation so you should reuse the file that has been uploaded at that point.

    I believe maybe you should validate the file upload before the event uploadComplete is actually triggered, so that the validation will be able to return whether upload is completed or failed (due to validation issues, for example).
    Fabrício Murta
    Developer & Support Expert
  3. #3

    Any example?

    Thanks for the reply, sorry I haven't seen this thread for a while.
    Is there any example or link to do custom validation like that?
    I only knew how to use basic validation such as allowed file size, file type, etc.

    Thanks
  4. #4
    Hello @Kuro13!

    Below I've modified the same example you used as base and added server-side validation. That is, the uploaded file will be handled by the server and it will return error if the validation failed.

    There are two approaches shown:
    1. return an error response to the upload process
    2. call a custom function to mark the upload as invalid

    Further code were changed to allow in the second approach for an error message to be attached to the grid entry.

    <%@ Page Language="C#" %>
    
    <script runat="server">
        protected void MultiUpload1_FileUpload(object sender, FileUploadEventArgs e)
        {
            // Approach #1: Passes an error status from the page to SWF upload, that will signal
            // the upload failed.
            if (e.FileBytes.Length > 1024)
            {
                Response.StatusCode = 403;
                Response.StatusDescription = "File size too big.";
                return;
            }
                
            // Approach #2: Calls a failure handler if the file contents do not match our criteria
            if (e.FileBytes.Length < 50 || e.FileBytes[2] != 'g')
            {
                Response.Write("bleh");
                X.Msg.Notify("File not uploaded", "File is too small or format does not match.").Show();
                X.AddScript("triggerValidationError('Invalid file format.');");
            }
            else
            {
                X.Msg.Notify("File is uploaded", "Name: " + e.FileName).Show();
            }
        }
    </script>
    
    <!DOCTYPE html>
    
    <html>
    <head runat="server">
        <title>Grid MultiUpload - Ext.NET Examples</title>
        <link href="/resources/css/examples.css" rel="stylesheet" />
    
        <script>
            var sendingStatusText = "Sending";
    
            var loadFailed = function () {
                alert("Something went wrong while loading SWFUpload. If this were a real application we'd clean up and then give you an alternative");
            };
    
            var statusIconRenderer = function (value) {
                // Handle the icon rendering if there's a status error message on the column.
                var val = value;
                if (value.length > 5 && value.substr(0, 6) == "Error:") {
                    val = "Error:";
                }
    
                switch (val) {
                    default:
                        return value;
                    case 'Pending':
                        return '<img src="' + Ext.net.ResourceMgr.getIconUrl("Hourglass") + '" width=16 height=16>';
                    case 'Sending':
                        return '<div src="x-loading-indicator" width=16 height=16>';
                    case 'Error':
                        return '<img src="' + Ext.net.ResourceMgr.getIconUrl("Decline") + '" width=16 height=16>';
    
                    // For the error with message, add the message to the icon on hover.
                    case 'Error:':
                        return '<img src="' + Ext.net.ResourceMgr.getIconUrl("Decline") + '" width=16 height=16 alt="' + value.replace('"', '&quot;') + '" title="' + value.replace('"', '&quot;') + '">';
                    case 'Cancelled':
                    case 'Aborted':
                        return '<img src="' + Ext.net.ResourceMgr.getIconUrl("Decline") + '" width=16 height=16>';
                    case 'Uploaded':
                        return '<img src="' + Ext.net.ResourceMgr.getIconUrl("Tick") + '" width=16 height=16>';
                }
            };
    
            var updateRecord = function (id, field, value) {
                var rec = App.UploadGrid.store.getById(id);
    
                rec.set(field, value);
                rec.commit();
            };
    
            var abortUpload = function (btn) {
                var selModel = btn.up('grid').getSelectionModel(),
                    records;
    
                if (!selModel.hasSelection()) {
                    Ext.Msg.alert('Error', 'Please select an upload to cancel');
                    return true;
                }
    
                records = selModel.getSelection();
                App.MultiUpload1.abortUpload(records[0].getId());
            };
    
            var removeUpload = function (btn) {
                var selModel = btn.up('grid').getSelectionModel(),
                    records;
    
                if (!selModel.hasSelection()) {
                    Ext.Msg.alert('Error', 'Please select an upload to remove');
                    return true;
                }
    
                records = selModel.getSelection();
                App.MultiUpload1.removeUpload(records[0].getId());
            };
    
            var fileSelected = function (item, file) {
                // Example of cancelling a file
                if (file.name == 'image.jpg') {
                    Ext.Msg.alert('Error', 'You cannot upload the file named "image.jpg"');
                    return false;
                }
    
                this.up('grid').store.add({
                    id: file.id,
                    name: file.name,
                    size: file.size,
                    status: 'Pending',
                    progress: 0
                });
            };
    
            var uploadError = function (item, file, errorCode, message) {
                updateRecord(file.id, 'progress', 0);
                updateRecord(file.id, 'status', 'Error');
    
                switch (errorCode) {
                    case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
                        alert("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
                        break;
                    case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
                        alert("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                        break;
                    case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                        alert("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
                        break;
                    case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
                        alert("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
                        break;
                    case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                        alert("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                        break;
                    case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
                        alert("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                        break;
                    case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                        updateRecord(file.id, 'status', 'Cancelled');
                        break;
                    case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                        updateRecord(file.id, 'status', 'Stopped');
                        break;
                    default:
                        updateRecord(file.id, 'status', "Unhandled Error: " + errorCode);
                        alert("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                        break;
                }
            };
    
            var fileSelectionError = function (item, file, errorCode, message) {
                if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
                    alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
                    return;
                }
    
                switch (errorCode) {
                    case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                        alert("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                        break;
                    case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                        alert("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                        break;
                    case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                        alert("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                        break;
                    default:
                        alert("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                        break;
                }
            };
    
            // Approach #2, marking file upload as failed.
            var triggerValidationError = function(msg) {
                var currEntry = App.UploadGrid.store.findRecord('status', sendingStatusText);
    
                if (currEntry && currEntry.data && currEntry.data.status) {
                    updateRecord(currEntry.id, 'status', 'Error: ' + msg);
                }
            }
    
            // Will only update on complete if status is currently 'sending'.
            var handleUploadComplete = function (multiuploadComponent, fileInfo) {
                var gridEntry = App.UploadGrid.store.getById(fileInfo.id);
                updateRecord(fileInfo.id, 'progress', 1);
    
                if (gridEntry.status == sendingStatusText) {
                    updateRecord(fileInfo.id, 'status', 'Uploaded');
                }
            }
        </script>
    </head>
    <body>
        <form runat="server">
            <ext:ResourceManager runat="server" />
    
            <ext:GridPanel
                ID="UploadGrid"
                runat="server"
                Width="560"
                Height="300"
                Frame="true">
                <Store>
                    <ext:Store runat="server">
                        <Model>
                            <ext:Model runat="server" IDProperty="id">
                                <Fields>
                                    <ext:ModelField Name="id" />
                                    <ext:ModelField Name="name" />
                                    <ext:ModelField Name="size" />
                                    <ext:ModelField Name="status" />
                                    <ext:ModelField Name="progress" />
                                </Fields>
                            </ext:Model>
                        </Model>
                    </ext:Store>
                </Store>
                <ColumnModel>
                    <Columns>
                        <ext:Column runat="server" Text="File Name" DataIndex="name" Width="150" />
                        <ext:Column runat="server" Text="Size" DataIndex="size" Width="60">
                            <Renderer Format="FileSize" />
                        </ext:Column>
                        <ext:Column runat="server" Text="&nbsp;" DataIndex="status" Width="30">
                            <Renderer Fn="statusIconRenderer" />
                        </ext:Column>
                        <ext:Column runat="server" Text="Status" DataIndex="status" Width="60" />
                        <ext:ProgressBarColumn runat="server" Text="Progress" DataIndex="progress" />
                    </Columns>
                </ColumnModel>
                <TopBar>
                    <ext:Toolbar runat="server">
                        <Items>
                            <ext:MultiUpload
                                ID="MultiUpload1"
                                runat="server"
                                OnFileUpload="MultiUpload1_FileUpload"
                                FileDropAnywhere="true"
                                FileSizeLimit="15 MB"
                                FileTypes="*.*"
                                FileTypesDescription="All Files"
                                FileUploadLimit="100"
                                FileQueueLimit="0">
                                <Listeners>
                                    <SwfUploadLoadFailed Fn="loadFailed" />
                                    <FileSelected Fn="fileSelected" />
                                    <UploadStart Handler="updateRecord(file.id, 'status', sendingStatusText);" />
                                    <UploadProgress Handler="updateRecord(file.id, 'progress', bytesComplete / bytesTotal);" />
                                    <UploadComplete Fn="handleUploadComplete" />
                                    <UploadAborted Handler="updateRecord(file.id, 'status', 'Aborted');" />
                                    <UploadRemoved Handler="var store = this.up('grid').store; store.remove(store.getById(file.id));" />
                                    <UploadError Fn="uploadError" />
                                    <FileSelectionError Fn="fileSelectionError" />
                                </Listeners>
                            </ext:MultiUpload>
    
                            <ext:ToolbarSeparator />
    
                            <ext:Button
                                runat="server"
                                Text="Start Upload"
                                Icon="Tick"
                                Handler="#{MultiUpload1}.startUpload();" />
                            <ext:Button
                                runat="server"
                                Text="Abort"
                                Icon="Decline"
                                Handler="abortUpload" />
                            <ext:Button
                                runat="server"
                                Text="Abort All"
                                Icon="Decline"
                                Handler="#{MultiUpload1}.abortAllUploads();" />
                            <ext:Button
                                runat="server"
                                Text="Remove"
                                Icon="Delete"
                                Handler="removeUpload" />
                            <ext:Button
                                runat="server"
                                Text="Remove All"
                                Icon="Delete"
                                Handler="#{MultiUpload1}.removeAllUploads();" />
                        </Items>
                    </ext:Toolbar>
                </TopBar>
            </ext:GridPanel>
        </form>
    </body>
    </html>
    Hope this helps!
    Fabrício Murta
    Developer & Support Expert
  5. #5
    Hi Fabricio,

    Thank you so much for the code. It works.
    So basically, validating file from OnFileUpload and trigger validation Error (triggerValidationError) in javascript to search for row that are in sending status and update it to failed.
    But I have a question, is there any possibility that the upload will have more than one row in sending status? maybe when user drag and drop multiple file at once? because if that happen, than all the sending status will updated to failed even if only one is failed. Or is there any way to update according to file id or row index not by status?

    Thanks.
  6. #6
    Hello!

    The multiupload sends only one file per time and it does not pass the gridpanel entry's ID to code behind (as the multiupload SWF component itself has no idea of nor is related to the grid at all). So at least in the example above, the files will all be set in the 'pending' state until the individual download starts, and it will not (likely) have conflicts in that scenario.

    If you are to change uploading so it sends several files at once, then you will have to adapt the example accordingly to deal with concurrent uploads at once. Probably you'll need to use different multiupload components to do more than one upload at a time. If that's the case you can bind to the multiupload component a variable containing the ID of the row being currently worked on so the validator can query it even though code behind does not know about it. The code behind event call with the file upload is made from the SWF Multiupload module so we can't really control what goes there and what not.

    Hope this helps!
    Fabrício Murta
    Developer & Support Expert

Similar Threads

  1. Replies: 24
    Last Post: Dec 19, 2015, 11:01 AM
  2. [CLOSED] Get uploaded file name and file path server side.
    By speedstepmem4 in forum 2.x Premium Help
    Replies: 9
    Last Post: Jul 31, 2014, 11:24 AM
  3. MultiUpload Last file uploaded event
    By stebag in forum 2.x Help
    Replies: 1
    Last Post: Jan 19, 2014, 1:28 PM
  4. Replies: 5
    Last Post: Oct 07, 2013, 2:44 PM
  5. How to access/read from uploaded file
    By KBorkiewicz in forum 2.x Help
    Replies: 3
    Last Post: Nov 21, 2012, 4:32 PM

Tags for this Thread

Posting Permissions