Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restrict the file type in the file browse menu of an AsyncFileUpload in the ASP.NET AJAX Control Toolkit

I would like to restrict what they see in the file upload dialog, which is set to "All Files" by default. I understand how to validate that they only uploaded a certain file type, that is not the question here. I would just like to know how to default the file type in the file selection dialog.

Is there any way to change this to "PNG only" or "*.png"?

This is using AsyncFileUpload in the ASP.NET AJAX Control Toolkit.

like image 499
SteveGSD Avatar asked Jul 28 '10 21:07

SteveGSD


2 Answers

This one is working for me (Thanks DavRob for the inspiration).

<cc1:AsyncFileUpload ID="FileUpload" runat="server" 
  OnClientUploadStarted="AssemblyFileUpload_Started" />

<script>
function AssemblyFileUpload_Started(sender, args) {
    var filename = args.get_fileName();
    var ext = filename.substring(filename.lastIndexOf(".") + 1);
    if (ext != 'png') {
        throw { 
            name:        "Invalid File Type", 
            level:       "Error", 
            message:     "Invalid File Type (Only .png)",
            htmlMessage: "Invalid File Type (Only .png)" 
        }
        return false;
    }
    return true;
}
</script>
like image 172
msaiz Avatar answered Nov 07 '22 22:11

msaiz


You can use the OnClientUploadStart property on the control to fire a JavaScript function for validation, like this:

<cc1:AsyncFileUpload ID="FileUpload" runat="server" 
  OnClientUploadStarted="checkExtension" />

Then have this script in your page or included:

function checkExtension(sender, args) {
  var ext = args.get_fileName().substring(filename.lastIndexOf(".") + 1);
  if (ext != 'png') {
    args.set_cancel(true);                           //cancel upload
    args.set_errorMessage("File type must be .png"); //set error message
    return false;
  }
  return true;
}

In this case we're just using various bits of the client-side API to get/check the extension, returning false and stopping the upload/setting the error message (optional) if it's invalid.

like image 24
Nick Craver Avatar answered Nov 08 '22 00:11

Nick Craver