help me understand the following javascript relate to AsyncFileUpload control - asp.net

in my current project I used a AsyncFileUpload control from AJAX Control Toolkits. After I got the async file upload part working, I needed to filter the file type so users can only upload image files. I found the following code off web and it worked well:
function uploadStarted(sender, args) {
var filename = args.get_fileName();
var filext = filename.substring(filename.lastIndexOf(".") + 1);
if (filext == "jpg" || filext == "jpeg" || filext == "gif" || filext == "bmp") {
return true;
}
else
{
// force uploading cancel
args.set_cancel(true);
// set reason of cancel
args.set_errorMessage("Invalid File Format Selected");
return false;
}
}
The problem is : I don't understand this javascript. What is the type of args parameter? Where are the methods such as "get_fileName()", "set_cancel()" defined? I went to the homepage of the AsyncFileUpload control but couldn't find any documentation regarding the "args".
Can someone help me out explaining this Javascript? Thanks

I think I can answer my own question
The first parameter identifies the object that fired the event, while the second provides information on the file being uploaded. In fact, it contains five useful properties accessed using the get_abc() syntax demonstrated above.
get_fileName() and get_path() both return the name of the file being uploaded
get_length() returns the size of the file in bytes once uploaded. Returns null prior to upload
get_contentType() returns the mime type of the file once it is uploaded. Returns null prior to upload
get_errorMessage() returns an error message should one occur. Returns null otherwise
For more details refer to this article:
http://p2p.wrox.com/content/blogs/danm/enter-asyncfileupload-control

Related

how to read additional parameters in alfresco 5.1.1- aikau faceted search

Custom Search UI will be populated when user selects Complex asset in the Advance search screen drop down(apart from Folders,Contents) where 12 fields will be displayed .So when user clicks search button ,need to read those values and redirect to the alfresco repo files(org/alfresco/slingshot/search/search.get.js).We have already customized these files(search.get.js,search.lib.js) existed in the repository to suit out logic and working fine in 4.2.2;As we are migrating to 511,so we need to change this logic in customized faceted-search.get.js to read these values.How to write this logic in customized facted-search.get.js?
It's not actually possible to read those URL hash attributes in the faceted-search.get.js file because the JavaScript controller of the WebScript does not have access to that part of the URL (it only has information about the URL and the request parameters, not the hash parameters).
The hash parameters are actually handled on the client-side by the AlfSearchList widget.
Maybe you could explain what you're trying to achieve so that I can suggest an alternative - i.e. the end goal for the user, not the specifics of the coding you're trying to achieve.
We will be reading the querystring values something like below in the .get.js file.
function getNodeRef(){
var queryString = page.url.getQueryString();
var nodeRef = "NOT FOUND";
var stringArray = queryString.split("&");
for (var t = 0; t < stringArray.length; t++) {
if (stringArray[t].indexOf('nodeRef=') > -1) {
nodeRef = stringArray[t].split('=')[1];
break;
}
}
if (nodeRef !== "NOT FOUND") {
nodeRef = nodeRef.replace("://", "/");
return nodeRef;
}
else {
throw new Error("Node Reference is not found.");
}
}
It may be help you and we will wait for Dave Drapper suggestion also.

validate asp fileupload control client side

i have a asp fileupload control on my page. how to validate the selected file on client side.
validation rules:
1. file must be jpeg,png,bmp or gif.
2. file size must be within 25 kb and 2 mb.
please help.
thanks.
I Have Tried The Following Code to validate the extension
<asp:FileUpload ID="FileUpload2" runat="server"/>
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateFileUpload" ErrorMessage="Invalid file type. Only .gif, .jpg, .png, .bmp and .jpeg are allowed." ControlToValidate="FileUpload2" ValidationGroup="update"> </asp:CustomValidator>
<script language="javascript" type="text/javascript">
function ValidateFileUpload(Source, args) {
var fuData = document.getElementById('<%= fuData.ClientID %>');
var FileUploadPath = fuData.value;
if (FileUploadPath == '') {
// There is no file selected
args.IsValid = false;
}
else {
var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
if (Extension == "jpg" || Extension == "jpeg" || Extension == "png" || Extension == "gif" || Extension == "bmp") {
args.IsValid = true; // Valid file type
}
else {
args.IsValid = false; // Not valid file type
}
}
}
</script>
You cannot determine the size of the file selected in the file input element via client side script. In order to determine the size of the file, one must have read access to the file. As you may imagine, allowing JavaScript to read files on your computer would be a "really bad idea."™
I often see this type of question, and believe that there is some confusion about what the file input element actually does. When the user selects a file, the file bytes aren't "loaded" into this element such that they are available for reading. Rather, the input specifies a reference to the file location so that the browser knows - when the form is posted - to encode the file and send it with the POST. This process is internal to the browser, and isn't exposed to the client in a manner that it can be leveraged by script.
If you need to do file size verification, you should do it on the server where you have access to the actual file bytes. If you are concerned with people "flooding" your site with very large files, you can specify the maximum allowable POST size by configuring your IIS instance.
You can try out ajax control tool kit. It has its own control for file upload. Its much more cool
In most browsers used nowadays, you can do client-side validation on file size:
https://stackoverflow.com/a/1832497/2705769

file upload control problem

i am using file upload control in server side when iam trying to get the file it is showing no file present
<asp:FileUpload ID="upldDocument" runat="server" />
string fileExtension = System.IO.Path.GetExtension(upldDocument.FileName);
if (upldDocument.HasFile)
{
}
i am getting a empty string as file extension and upldDocument.HasFile is returning false even after selecting a file.
what could be the reason??
Based on the posted code, I can only offer a best guess. There's not enough code posted to be sure what the problem is, but here's my best guess:
If you're not already, you need to check the HasFile property.
See here for a full example:
Edit - added
Using HasFile AFTER the bad code won't help. You need to put the code to get the extention inside an if statement so that it only attempts to read the extension if there IS a file.
string fileExtension = "";
if (upldDocument.HasFile)
{
fileExtension = System.IO.Path.GetExtension(upldDocument.FileName);
}
else
{
//No file selected by user, which is why you can't get the extension.
// handle this eventuality here even if it means just returning from the function and not doing anything.
}
How are you checking the values? (in what event)
Did you set the enctype attribute of the form to "multipart/form-data" ?

WMF image data validation?

There is an image capturing device which gives its output in wmf. This output is stored in the database directly. We have cases where at times some of these images do not appear on a web page in IE. But if we right click on the page we are able to save the image on to the hard disk; meaning the image does exist on the page, but does not appear visible. I think this is because of some file corruption issue, but I don't know how to resolve it. We are however able to view such files using MS Picture Viewer (desktop app). Is there anyway we can detect such problematic files?
I hope I am not being over simplistic over this but the following function works for me:
public bool IsValidMetaFile(string filePath)
{
try
{
var metaFile = new Metafile(filePath);
var metaFileHeader = metaFile.GetMetafileHeader();
return metaFileHeader.IsWmf() ||
metaFileHeader.IsWmfPlaceable() ||
metaFileHeader.IsEmf() ||
metaFileHeader.IsEmfPlusDual() ||
metaFileHeader.IsEmfPlusOnly() ||
metaFileHeader.IsEmfOrEmfPlus();
}
catch (Exception mesg)
{
return false;
}
}

Add filter to FileUpload Control

How to add filter to the fileupload control in asp.net? I want a filter for Word Template File (.dot).
You could also do a javascript alternative to filtering it server side (you'd probably want to do that as well) but this saves the client from spending the time waiting on an upload to finish just to find out it was the wrong type.
http://javascript.internet.com/forms/upload-filter.html
So basically you just run a javascript function on submit that parses off the extension of the uploaded file and gives them an alert if its not of the right type.
You could also use document.forms[0].submit(); instead of passing the form reference through (as ASP.NET really only uses a single form (unless your doing something funky))
string fileName = fuFiles.FileName;
if(fileName.Contains(".dot"))
{
fuFiles.SaveAs(Server.MapPath("~/Files/" + fileName));
}
If you mean to filter the file extensions client/side, with the standard browser's file selector, isn't possible.
To do that you have to use a mixed type of upload, such as SWFUpload, based on a flash uploader system (that's a really nice techinque: it allows you to post more than a file at time).
The only thing you can do in standard mode is to filter the already posted file, and I suggest to use System.IO.Path namespace utility:
if (Path.GetExtension(upFile.FileName).ToUpper().CompareTo(".DOT") == 0)
{
/* do what you want with file here */
}
Check the filename of the uploaded file serverside:
FileUpload1.PostedFile.FileName
Unless you want to use java or something similar on the client, there's really not much you can do for filtering uploaded files before they're sent to the server.
Here I have a small method that I used to filter which types of files can be uploaded by the fileupload control named fuLogo.
if (fuLogo.HasFile)
{
int counter = 0;
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]);
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++;
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
fuLogo.SaveAs(logo);
}
basically, I first Iterates through the directory to see if a file already exists. Should the file exist, (example picture0.gif) , it will increase the counter (to picture1.gif). It prevents that different users will overwrite each other's pictures should their pictures have the same name.

Resources