I have am AsyncFileUpload Control like this
<ajaxToolkit:AsyncFileUpload
OnUploadedComplete="Attachment1_UploadedComplete"
OnClientUploadStarted="Attachment1_UploadStarted" runat="server"
ID="Attachment1File" AutoPostBack="true"
UploaderStyle="Traditional" CssClass="form-control"
UploadingBackColor="#CCFFFF" ThrobberID="loader1" />
I want allowed files to be doc,docx,pdf,xls,xlsx,zip and max file upload 10MB. How can I validate file before uploading?
I tried to do something like this in the codebehind but the file is already uploaded to the server when this executes
AttachmentError1.Visible = false;
string[] extension = Attachment1File.PostedFile.FileName.Split('.');
if (Attachment1File.PostedFile.ContentLength > 100000000 || !Extensions.Contains(extension[extension.Length-1]))
{
File.Delete(Server.MapPath("~/FormTemporaryFiles/") + FormId + "\\" + FormIdNumber.Value + "\\" + e.FileName.ToString());
Attachment1File.ClearAllFilesFromPersistedStore();
AttachmentError1.Visible = true;
}
Edit: I tried to use a custom validator but it didn't work.
What I did is add the code to the codebehind in the UploadedCompleted Event of the AsyncFileUpload and chech again at the button submit. Custom Validator did not work, so I had to do it manually.
I have an image control and a file upload control in .NET 2.0 (VS.NET 2008) form. As soon as user selects an image file in the file upload control, i want the image to appear in the image control of the form. What would be the way to do this ?
(The only event File Upload seems to support is 'OnChange' and i don't know enough javascript to update Image1.URL based on content of FileUpload).
Thanks,
Chak.
You need to upload Asynchronously , and you could try AJAX AsyncFileUpload and this is what you are looking...
http://asp.net-informations.com/ajax/ajax-AsyncFileUpload.htm
Are you looking for a kind of preview? You can only show the image to the user after the file has been uploaded. I'm pretty sure the user has to actively do so (otherwise you could try to read the entire filesystem from the browser)
I think this is a good example:
http://www.codeproject.com/KB/ajax/AJAXUpload.aspx
this is a good starting point too:
http://www.eggheadcafe.com/community/aspnet/2/10204276/how-to-display-image-when-upload-image.aspx
or here:
http://www.eggheadcafe.com/community/aspnet/2/10236947/image-upload-and-display.aspx
updated
protected void Button4_Click(object sender, EventArgs e)
{
string strExtn;
string strpostedfile;
strpostedfile = fileuploading.PostedFile.FileName;
strExtn = System.IO.Path.GetExtension(strpostedfile);
strExtn = strExtn.ToLower();
string strEx = Path.GetExtension(fileuploading.PostedFile.FileName).ToLower();
String filename = Path.GetFileName(fileuploading.FileName);
filename = filename.Remove(filename.Length - strEx.Length);
fileuploading.SaveAs(Server.MapPath("~/Photos/") + filename);
uploadImage.ImageUrl = "~/Photos/" + filename;
}
Page:
<asp:FileUpload ID="fileuploading" runat="server" />
<asp:Button ID="Button4" runat="server" onclick="Button4_Click" Text="Button" />
<br />
<asp:Image ID="uploadImage" runat="server" />
In Crystal Reports Viewer (2008) for ASP.Net, when you click on the Export button, the Export dialog shows up with File Format options:
Crystal Reports (RPT)
PDF
Microsoft Excel(97-2003)
Microsoft Excel(97-2003) Data-Only
Microsoft Word (97-2003)
Microsoft Word (97-2003) Editable
Rich Text Format (RTF)
XML
etc..
Does anyone know how to remove some of these options so that end users wouldn't see it?
We've ran into this same issue and ended up rolling our own export page and limited the selection there.
It works great, but I would have expected more from Crystal Reports!
From what I was able to find, you could try to create your own export button option, removing the given button option and adding your own to the asp page. You would need to start by dragging the button onto the page and double clicking it to auto generate the code. From there add the code
crystalReportViewer1.ExportReport ()
Once this code is in it will use the default settings for the export options, however if you want to change the export options within that button then you have to manually code it.
' Declare variables and get the export options.
Dim exportOpts As New ExportOptions()
Dim diskOpts As New DiskFileDestinationOptions()
Dim excelFormatOpts As New ExcelFormatOptions()
exportOpts = Report.ExportOptions
' Set the excel format options.
excelFormatOpts.ExcelTabHasColumnHeadings = true
exportOpts.ExportFormatType = ExportFormatType.Excel
exportOpts.FormatOptions = excelFormatOpts
' Set the export format.
exportOpts.ExportFormatType = ExportFormatType.Excel
exportOpts.ExportDestinationType = ExportDestinationType.DiskFile
' Set the disk file options.
diskOpts.DiskFileName = fileName
exportOpts.DestinationOptions = diskOpts
Report.Export()
MSDN SITE
This link gives you the same code posted above. It show how to do it in Visual Basic code. therefor in your aspx.vb code you would have to manually enter the the types of formats you want.
You might be able to control the export options by removing the export DLLs. Search for crxf_*.dll in the Business Objects\Common\\bin directory.
Refer Below Answer to remove unwanted export Option from Crystal Reports
Display PDF and Excel export options in Crystal Reports?
<asp:ImageButton Width="20px" Height="20px" ID="btnPdf" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/PDF.png" AlternateText="Export To PDF" CssClass="AddedButton" />
<asp:ImageButton Width="20px" Height="20px" ID="btnXls" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/XLS.png" AlternateText="Export To Excel" />
<asp:ImageButton Width="20px" Height="20px" ID="btnDoc" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/DOC.png" AlternateText="Export To Word" />
try this:
<CR:CrystalReportViewer ... HasExportButton="false" HasPrintButton="False" >
<asp:ImageButton Width="20px" Height="20px" ID="btnPdf" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/PDF.png" AlternateText="Export To PDF" CssClass="AddedButton" />
<asp:ImageButton Width="20px" Height="20px" ID="btnXls" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/XLS.png" AlternateText="Export To Excel" />
<asp:ImageButton Width="20px" Height="20px" ID="btnDoc" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/DOC.png" AlternateText="Export To Word" />
C# code:
protected void btnExport_Click(object sender, EventArgs e)
{
// Stop buffering the response
Response.Buffer = false;
// Clear the response content and headers
Response.ClearContent();
Response.ClearHeaders();
try
{
string senderID = ((ImageButton)sender).ID;
if (senderID == "btnPdf")
reportDocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, Page.Title);
else if (senderID == "btnXls")
reportDocument.ExportToHttpResponse(ExportFormatType.ExcelRecord, Response, true, Page.Title);
else if (senderID == "btnDoc")
reportDocument.ExportToHttpResponse(ExportFormatType.WordForWindows, Response, true, Page.Title);
// There are other format options available such as Word, Excel, CVS, and HTML in the ExportFormatType Enum given by crystal reports
}
catch (System.Threading.ThreadAbortException)
{
//The issue has been identified and logged under Problem Report ID
//ADAPT00765364. The error is likely caused because Response.End() is used inside the
//ExportToHttpResponse() method.
//It is a known issue that Reponse.End() causes the thread to abort. This is by design.
//See Microsoft KB312629 Article for more info.
}
catch (Exception ex)
{
//error management
}
}
Apparently a later version (13.0?) adds a AllowedExportFormats property to the CrystalReportViewer class.
I don't have that newer version (I just have 12.0) but apparently something like this is all you need:
int exportFormatFlags = (int)
(CrystalDecisions.Shared.ViewerExportFormats.PdfFormat |
CrystalDecisions.Shared.ViewerExportFormats.ExcelFormat |
// any other desired formats
);
crystalReportViewer1.AllowedExportFormats = exportFormatFlags;
using (ReportClass rptH = new ReportClass())
{
rptH.FileName = #"C:/Report/crJournal.rpt"; //Your rpt file path
// if you put your rpt file on Bin then you need to write only rpt file name
rptH.Load();
rptH.SetDataSource( ds );// Provide Dataset for report : Ds is DataSet
rptH.ExportToDisk(ExportFormatType.Excel, "Give Output file path");
}
This code is defenetly work :
I have a webform that has an ASP file upload object and I want to use jQuery to grab the file they have selected and upload the file via AJAX.
However I am having problems grabbing the file name after it's been selected.
Here is the HTML/ASP Code:
<asp:FileUpload runat="server" ID="NewPic" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="NewPic" runat="server" Display="Dynamic" Text="You need to pick a picture." CssClass="mandatory"></asp:RequiredFieldValidator>
This is what I have tried but doesn't seem to work
uploadText = $('input[type=file]').value;
alert('FileName: ' + uploadText);
Give this a try:
uploadText = $(':file').val();
alert('FileName: ' + uploadText);
I post this even though I'm unsure if input[type=file] behaves differently than input[type=text]. But with input[type=text], you call the val() function and not read a value member variable.
I am using <input type="file" id="fileUpload" runat="server"> to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions).
Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).
Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.
HTML:
<input type="file" name="FILENAME" size="20" onchange="check_extension(this.value,"upload");"/>
<input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />
Javascript:
var hash = {
'xls' : 1,
'xlsx' : 1,
};
function check_extension(filename,submitId) {
var re = /\..+$/;
var ext = filename.match(re);
var submitEl = document.getElementById(submitId);
if (hash[ext]) {
submitEl.disabled = false;
return true;
} else {
alert("Invalid filename, please select another file");
submitEl.disabled = true;
return false;
}
}
It's pretty simple using regulare expression validator.
<asp:RegularExpressionValidator
id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Only zip file is allowed!"
ValidationExpression ="^.+(.zip|.ZIP)$"
ControlToValidate="FileUpload1"
> </asp:RegularExpressionValidator>
Client-Side Validation of File Types Permissible to Upload
From javascript, you should be able to get the filename in the onsubmit handler. So in your case, you should do something like:
<form onsubmit="if (document.getElementById('fileUpload').value.match(/xls$/) || document.getElementById('fileUpload').value.match(/xlsx$/)) { alert ('Bad file type') ; return false; } else { return true; }">...</form>
I agree with Chris, checking the extension is not validation of the type of file any way you look at it. Telerik's radUpload is probably your best option, it provides a ContentType property of the file being uploaded, which you can compare to known mime types. You should check for:
application/vnd.ms-excel,
application/excel,
application/x-msexcel
and for the new 2k7 format:
application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet
Telerik used to sell radUpload as an individual component, but now its wrapped into the controls suite, which makes it a little more expensive, but by far its the easiest way to check for the true type
You could use a regular expression validator on the upload control:
<asp:RegularExpressionValidator id="FileUpLoadValidator" runat="server" ErrorMessage="Upload Excel files only." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.xls|.XLS|.xlsx|.XLSX)$" ControlToValidate="fileUpload"> </asp:RegularExpressionValidator>
There is also the accept attribute of the input tag:
<input type="file" accept="application/msexcel" id="fileUpload" runat="server">
but I did not have much success when I tried this (with FF3 and IE7)
As some people have mentioned, Javascript is the way to go. Bear in mind that the "validation" here is only by file extension, it won't validate that the file is a real excel spreadsheet!
Based on kd7's reply suggesting you check for the files content type, here's a wrapper method:
private bool FileIsValid(FileUpload fileUpload)
{
if (!fileUpload.HasFile)
{
return false;
}
if (fileUpload.PostedFile.ContentType == "application/vnd.ms-excel" ||
fileUpload.PostedFile.ContentType == "application/excel" ||
fileUpload.PostedFile.ContentType == "application/x-msexcel" ||
fileUpload.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" //this is xlsx format
)
return true;
return false;
}
returning true if the file to upload is .xls or .xlsx
Ensure that you always check for the file extension in server-side to ensure that no one can upload a malicious file such as .aspx, .asp etc.
Well - you won't be able to do it server-side on post-back as the file will get submitted (uploaded) during the post-back.
I think you may be able to do it on the client using JavaScript. Personally, I use a third party component called radUpload by Telerik. It has a good client-side and server-side API, and it provides a progress bar for big file uploads.
I'm sure there are open source solutions available, too.
I think there are different ways to do this. Since im not familiar with asp i can only give you some hints to check for a specific filetype:
1) the safe way: get more informations about the header of the filetype you wish to pass. parse the uploaded file and compare the headers
2) the quick way: split the name of the file into two pieces -> name of the file and the ending of the file. check out the ending of the file and compare it to the filetype you want to allow to be uploaded
hope it helps :)
Avoid the standard Asp.Net control and use the NeadUpload component from Brettle Development: http://www.brettle.com/neatupload
Faster, easier to use, no worrying about the maxRequestLength parameter in config files and very easy to integrate.
As an alternative option, could you use the "accept" attribute of HTML File Input which defines which MIME types are acceptable.
Definition here
Your only option seems to be client-side validation, because server side means the file was already uploaded. Also the MIME type is usually dictated by the file extension.
use a JavaScript Framework like jQuery to overload the onsubmit event of the form. Then check the extension. This will limit most attempts. However if a person changes an image to extension XLS then you will have a problem.
I don't know if this is an option for you, but you have more client side control when using something like Silverlight or Flash to upload. You may consider using one of these technologies for your upload process.
As another respondent notes, the file type can be spoofed (e.g., .exe renamed .pdf), which checking for the MIME type will not prevent (i.e., the .exe will show a MIME of "application/pdf" if renamed as .pdf). I believe a check of the true file type can only be done server side; an easy way to check it using System.IO.BinaryReader is described here:
http://forums.asp.net/post/2680667.aspx
and VB version here:
http://forums.asp.net/post/2681036.aspx
Note that you'll need to know the binary 'codes' for the file type(s) you're checking for, but you can get them by implementing this solution and debugging the code.
Client Side Validation Checking:-
HTML:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClientClick = "return ValidateFile()" OnClick="btnUpload_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="" />
Javascript:
<script type ="text/javascript">
var validFilesTypes=["bmp","gif","png","jpg","jpeg","doc","xls"];
function ValidateFile()
{
var file = document.getElementById("<%=FileUpload1.ClientID%>");
var label = document.getElementById("<%=Label1.ClientID%>");
var path = file.value;
var ext=path.substring(path.lastIndexOf(".")+1,path.length).toLowerCase();
var isValidFile = false;
for (var i=0; i<validFilesTypes.length; i++)
{
if (ext==validFilesTypes[i])
{
isValidFile=true;
break;
}
}
if (!isValidFile)
{
label.style.color="red";
label.innerHTML="Invalid File. Please upload a File with" +
" extension:\n\n"+validFilesTypes.join(", ");
}
return isValidFile;
}
</script>