I'm trying to do some validation of some other fields on the page after the user clicks the upload button of the ajaxfileupload control. OnClientUploadStart is defined to fire before the upload starts. and it works. but I want to cancel the upload if the validation fails.
I tried doing "return false;" but that didn't work.
How can I cancel the upload?
if the validation fails then I want to cancel
function uploadStart(sender, args) {
var FileDescription = document.getElementById("FileDescription").value;
alert( FileDescription);
return false;
}
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1"
ThrobberID="myThrobber" OnUploadComplete="AjaxFileUpload1_UploadComplete"
ContextKeys="" OnClientUploadError="uploadError" OnClientUploadComplete="uploadComplete" OnClientUploadStart="uploadStart"
AllowedFileTypes="jpg,jpeg,doc,xls"
MaximumNumberOfFiles="1"
runat="server"/>
To start uploading manually you can use this script:
function startUpload(){
$get("<%= AjaxFileUpload1.ClientID %>_UploadOrCancelButton").click();
}
Cancel download large files (works only for browsers that support HTML5).
function uploadStartedAjax(sender, args) {
var maxFileSize = $('#MaxRequestLength').val();
for (var i = 0; i < sender._filesInQueue.length; i++) {
var file_size = sender._filesInQueue[i]._fileSize;
if (file_size > maxFileSize) {
sender._filesInQueue[i].setStatus("cancelled", Sys.Extended.UI.Resources.AjaxFileUpload_Canceled+' - too large(> ' + maxFileSize + ' byte)!');
sender._filesInQueue[i]._isUploaded = true;
} //End if
} //End for
return true;
}
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" MaximumNumberOfFiles="200" Width ="750px"
OnClientUploadStart="uploadStartedAjax" />
Related
<asp:FileUpload ID="FUpImg1" runat="server" CssClass="control-label" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="FUpImg1" ValidationExpression="(.*?)\.(jpg|png|JPG|PNG)$"
CssClass="text-danger" ErrorMessage="Please Upload .jpg, .png only" Display="Dynamic"></asp:RegularExpressionValidator>
its not working its directly going on server side not validate my image extension. what is wrong with above code?
Thanks in advance!
RegularExpressionValidator only validate when i upload anything in the FileUploader!
that why its not validate anything when its null and going on server side in my question.
i use customvalidator with js function because i have 5 different FileUploader and i have to pass same function.
function validateImageExtension(source, args) {
var reg = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.png|.jpeg)$/;
if (args.Value == "" || args.valueOf == null) {
args.IsValid = false;
source.innerText = "Image is Required*";
}
else {
//Checks with the control value.
if (reg.test(args.Value)) {
args.IsValid = true;
source.innerText = "";
}
else {
//If the condition not satisfied shows error message.
args.IsValid = false;
source.innerText = "Only .jpg, .png, .jpeg files are allowed!";
}
}
}
idk how it work btw. i just copy paste it from 5 different blogs.
i'm having issues with code that used to work, but now fails to run. I have a character counter on a textbox with the below code in the .aspx file:
<script>
var bName = navigator.appName;
function taLimit(taObj, maxL) {
if (taObj.value.length == maxL) return false;
return true;
}
function taCount(taObj, Cnt, maxL) {
objCnt = createObject(Cnt);
objVal = taObj.value;
if (objVal.length > maxL) objVal = objVal.substring(0, maxL);
if (objCnt) {
if (bName == "Netscape") {
objCnt.textContent = maxL - objVal.length;
}
else { objCnt.innerText = maxL - objVal.length; }
}
return true;
}
function createObject(objId) {
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
}
</script>
aspx:
<asp:TextBox ID="txtDescription" runat="server" Font-Names="Courier New"
TextMode="MultiLine" Width="398px" onKeyPress="return taLimit(this, 50)" onKeyUp="return taCount(this,'myCounter1', 50)"></asp:TextBox>
<br /><B><SPAN id='myCounter1'>50</SPAN></B>
This worked without problems before, but now i want a way to update the myCounter1 On page load, to show the correct remaining characters, i'm loading text from database into the textbox.
right now i'm using this:
ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "document.getElementById('myCounter1').textContent = 50 - " + txtDescription.Text.Length.ToString() + ";", true);
This works, it sets the character counter to the correct remaining characters. Now the issue is however, when text is typed in the textbox, the caracter counter won't update anymore dynamically. Could someone tell me why?
Using js. Put this inside your script:
<script type="text/javascript">
window.onload = function(){
taCount(document.getElementById('<%=txtDescription.ClientID%>'),'myCounter1', 50);
}
</script>
Remove the Server side scriptmanager code.
Here i am trying to execute two functions i.e. one javascript and one c# code on a single button click.The problem is both the functions are executing simultaneously.Here are my functions:
Javascript function
function exportCharts() {
var exportFormat = 'JPG';
initiateExport = true;
for (var chartRef in FusionCharts.items) {
if (FusionCharts.items[chartRef].exportChart) {
document.getElementById("linkToExportedFile").innerHTML = "Exporting...";
FusionCharts.items[chartRef].exportChart({ "exportFormat": exportFormat });
}
else {
document.getElementById("linkToExportedFile").innerHTML = "Please wait till the chart completes rendering...";
}
}
}
c# code:
protected void imgBTNExportPPT_Click(object sender, ImageClickEventArgs e)
{
try
{
PredictExportToPPT objOExporttoPPT = new PredictExportToPPT();
PredictionModel();
string reportNames = ObjCommon.GetBIReportNames("Prediction", "Report");
reportNames += ObjCommon.GetBIReportNames("Prediction", "Table");
objOExporttoPPT.ExportToPPTPredict(ObjPredictInputParameter, reportNames, ObjSharedEntities.PredictTableData);
string itemname = "PPTOutput.pptx";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "pptx";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + itemname + "");
HttpContext.Current.Response.BinaryWrite(System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(DataTemplate.PPTOutputTemplateFilePath)));
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception exceptionMessage)
{
throw (exceptionMessage);
}
finally
{
GC.Collect();
}
}
Button click code
<asp:ImageButton ID="imgBTNExportPPT" runat="server" Width="15" Height="15" border="0" OnClientClick="return exportCharts()" OnClick="imgBTNExportPPT_Click" />
If i try to use System.Threading.Thread.Sleep for the c# code,the javascript code is executing first but not completely.It waits till the execution of c# code and finally both the outputs are generated simultaneously.I want it to happen one after the other. Any suggestions?
I have tested it it is working
<asp:ImageButton ID="imgBTNExportPPT" runat="server" Width="15" Height="15" border="0" OnClientClick="exportReport()" OnClick="imgBTNExportPPT_Click" />
<script>
function exportReport() {
exportCharts();
__doPostBack("imgBTNExportPPT","");
}
</script>
If you are using master page, then:
replace
__doPostBack("imgBTNExportPPT","");
with
__doPostBack("ctl00$MainContent$imgBTNExportPPT", "");
I need to validate the file which is to be uploaded to the server. The validation must be done before uploading it. i.e., validation completed at client side. This task should be accomplished in ASP.NET MVC3 Webpage. It should also work with all browsers. IE9,8,7/FF/Chrome. I came to know that IE doesn't have FileReader API.
My Question is, How to Validate file size before Uploading in a MVC3 Webpage.
You can achieve by using jquery:
#
<span>
<b>Attachment</b> (8 MB only)<label id="attached" style="color:red; margin-left:5px"></label>
</span>
<input type="file" id="Attachment" name="Attachment" class="admin_textfeildmedium" value="" style="width:551px" accept="image/*">
#
jQuery(document).ready(function () {
jQuery('#Attachment').bind('change', function () {
//fileUpload = 0;
var iSize = (this.files[0].size / 1024);
if (iSize / 1024 > 1) {
if (((iSize / 1024) / 1024) > 1) {
fileUpload = 0;
} else {
iSize = (Math.round((iSize / 1024) * 100) / 100);
if (iSize <= 8) {
fileUpload = 1;
} else {
fileUpload = 0;
}
}
} else {
fileUpload = 1;
}
if (fileUpload == 0) {
// alert("Your attachment exceeded 8MB.");
jQuery('#attached').html('Your attachment exceeded 8MB.');
jQuery('#Attachment').val('');
}
});
});
.Net MVC Solution:
I am using the data type of HttpPostedFileBase
In your Views > Shared Folder, create a new folder called "EditorTemplates" and use this:
#model HttpPostedFileBase
#Html.TextBox("", null, new { type = "file" })
I then pass this HttpPostedFileBase object from the controller to a method that does the following:
public Files Upload(HttpPostedFileBase files)
{
if (files.ContentLength > 0) {
.....
}
The ContentLength property on the HttpPostedFileBase class contains the number of bytes in the posted file
This will make it so you have a file uploading box available.
On the ASP.NET WebForms Solution:
<asp:FileUpload ID="fuPictures" runat="server" />
Make a button with a OnClick or OnCommand event that does something like this:
if (fuPictures.HasFile == true)
{
int fileSize = fuPictures.FileBytes;
}
That will give you the file size. Hope this helps.
When it comes for a browser that supports HTML 5, it can be easily achieved with simple javascript:
Html Syntax
<input type="file" id="myFile" />
Javascript syntax
//gets the element by its id
var myFile = document.getElementById('myFile');
//binds to onchange event of the input field
myFile.addEventListener('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
BUT, when it comes to an older browser (and we are all looking to you, Internet Explorer), the only way to do that on the client side is by using ActiveX:
var myFile = document.getElementById('myFile');
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = myfile.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
I'm developing a web page for clients to request exemptions from certain requirements. There is a list of 14 CheckBoxes, each with two subsequent Checkboxes. The code to check which of them are checked will be placed in the submit button. This method is in the code behind. Here's the code for that (so far)
[WebMethod]
public void SendForm(string email)
{
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
else
{
if (IsValidEmailAddress(email))
{
bool[] desc = new bool[14];
bool[] local = new bool[14];
bool[] other = new bool[14];
for (int i = 1; i <= 14; i++)
{
desc[i] = ((CheckBox)Page.FindControl("chkDesc" + i.ToString())).Checked;
local[i] = ((CheckBox)Page.FindControl("chkLocal" + i.ToString())).Checked;
other[i] = ((CheckBox)Page.FindControl("chkOther" + i.ToString())).Checked;
/* Do stuff here */
}
}
else
{
throw new Exception("You must supply a valid email address.");
}
}
}
I get the error "An object reference iw required for the non-static field, method, or property..."
In the aspx page I have the button and the javascript/ajax that calls the button in the codebehind. Shown here:
<table width='750' align='center'>
<tr>
<td align='left'>
<label>Please Provide your email address:</label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align='left'>
</td>
</tr>
<tr>
<td align='left'>
<fieldset id="Fieldset">
<button onclick="SendForm();">
Send</button>
<button onclick="CancelForm();">
Cancel</button>
</fieldset>
</td>
</tr>
</table>
</form>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
PageMethods.SendForm(email, OnSucceeded, OnFailed);
}
function OnSucceeded() {
$get("Fieldset").innerHTML = "<p>Thank you!</p>";
}
function OnFailed(error) {
alert(error.get_message());
}
</script>
As per my knowledge, you can't refer to the controls of a page in the static method until and unless you explicitly pass a reference of the "Page" object to the web method you have written.
Where you have the following code:
bool[] desc = new bool[14];
bool[] local = new bool[14];
bool[] other = new bool[14];
for (int i = 1; i <= 14; i++)
{
desc[i] = ((CheckBox)Page.FindControl("chkDesc" + i.ToString())).Checked;
local[i] = ((CheckBox)Page.FindControl("chkLocal" + i.ToString())).Checked;
other[i] = ((CheckBox)Page.FindControl("chkOther" + i.ToString())).Checked;
/* Do stuff here */
}
Why don't you have this validation code in a Class in your project.. is there a reason why you are trying to access the PageControls using this code
if (IsValidEmailAddress(email))
{
for (int i = 1; i <= count; i++)
{
CheckBox chkBox = chkDesc1.Checked;
}
}
Change your for loop and start i = 0 and change <= 14 to < 13 C# is 0 based
Place the whole method signature .. you are probably trying to call a non static method inside of your application either add the word static to the method or remove but I would rather see how you have the method created.. also where are you creating the instance of the WebMethod Class object..?