I have been created upload image with edit and update.
When i insert image it will be stored both in hard drive and database.
If edit and upload another and click update, it will changed in gridview. but also i want to delete if already uploaded image in hard drive.
Here is my full source:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
string filepath = #"E\student\student\student\Images";
if (Directory.Exists(Path.GetDirectoryName(filepath)))
{
File.Delete(filepath);
}
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
com.Parameters.AddWithValue("#Image",(filename.Length>0)? "Images/" + filename:string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
string filename = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
com.Parameters.AddWithValue("#Image",(filename.Length>0)? "Images/" + filename:string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
}
May i know, how to delete if already uploaded image in the hard drive?
Any help would be highly appreciated.
Thanks,
Comment this code, is useless as well as wrong, SaveAs will overwright the file
string filepath = #"E\student\student\student\Images";
if (Directory.Exists(Path.GetDirectoryName(filepath)))
{
File.Delete(filepath);
}
if you really really want to delete:
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
if(File.Exists(Server.MapPath("~/Images/" + filename)))
File.Delete(Server.MapPath("~/Images/" + filename));
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
edit again:
string[] files = Directory.GetFiles(Server.MapPath("~/Images"));
foreach(string f in files) File.Delete (f);
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
Related
I have an excel file which I am trying to upload but its getting failed with error as below
The Microsoft Office Access database engine could not find the object 'Sheet1$'.
The error is causing at this line in the below code
da.Fill(dt);
And full code is below
private void UploadDataForAnyVendor(string strUser)
{
try
{
if (fluUploadBtn.HasFile)
{
string ConStr = "";
string ext = Path.GetExtension(fluUploadBtn.FileName).ToLower();
if (ext == ".xls" || ext == ".xlsx")
{
string path = Server.MapPath("~/UploadIPFEEData/");
//string strFolderName = "INDUS\\";
string strAnyFolder = "ANYFOLDER\\";
string strDeleteFile = Server.MapPath("~/ANYFOLDER/") + Path.GetFileName(fluUploadBtn.PostedFile.FileName);
string newPath = Path.Combine(path, strAnyFolder.ToString());
DirectoryInfo objDirectory = new DirectoryInfo(newPath);
string day = DateTime.Now.ToString("ss_mm_hh_dd_MM_yyyy");
if (!objDirectory.Exists)
{
System.IO.Directory.CreateDirectory(newPath);
newPath = newPath + fluUploadBtn.FileName;
}
newPath = newPath + fluUploadBtn.FileName;
if ((System.IO.File.Exists(fluUploadBtn.FileName)))
{
System.IO.File.Delete(fluUploadBtn.FileName);
}
if (ext.Trim() == ".xls")
{
ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + newPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (ext.Trim() == ".xlsx")
{
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + newPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection mycon = new OleDbConnection(ConStr);
if (mycon.State == ConnectionState.Closed)
{
mycon.Open();
}
OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", mycon);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(dt);
//loadfile(newPath, ext);
string strAssignedStates = string.Empty;
strAssignedStates = Convert.ToString(ViewState["States"]);
string strOne = strStates;
string[] strStateArray = new string[] { "" };
strStateArray = strOne.Split(',');
string errMsg = string.Empty;
int j = 1; string key = "StateNotFoundAlert" + j.ToString();
for (int i = 0; i < strStateArray.Length; i++)
{
if (dt.Rows[0]["CIRCLE"].ToString() == strStateArray[i].Trim().ToString())
{
if (dt.Rows.Count > 0)
{
errMsg = "1";
dt.TableName = "RecodSet";
string xml = ConvertDatatableToXML(dt);
mycon.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('File uploaded successfully.!!');", true);
}
else
{
string noData = "No data to upload.";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", noData, false);
}
}
else
{
errMsg = "0";
}
}
if (errMsg == "0" && errMsg != "1")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('User is not authorised to upload data for state mentioned in excel report ');", true);
}
}
else
{
string key = "Invalid vendor";
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('Invalid file extension !!!');", true);
}
}
}
catch (Exception)
{
throw;
}
}
Please suggest where I am going wrong
I have been created student details form by using aspx and c#.
In the image field i got some error.
What i have done:
Insert,edit and update image.
When i insert image and submit, I was set to display that image in gridview on the same page, and also save in "images" folder in my drive.
It works fine, but when i edit the image and upload new image and submit, the changed image didn't show in the gridview, but this changed image saved in "images" folder.
May i know, what is my mistake in my code?
Here is my source code:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("sp_updatestudentdetail", con);
com.CommandType = CommandType.StoredProcedure;
try
{
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
string[] files = Directory.GetFiles(Server.MapPath("~/Images"));
string uniqueFileName = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
foreach (string f in files) File.Delete(f);
filename = Path.GetFileName(fileupload.PostedFile.FileName);
string fileExtension = Path.GetExtension(filename).ToLower();
uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName));
}
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + filename : (uniqueFileName.Length > 0) ? "Images/" + uniqueFileName : string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
}
else
{
SqlCommand com = new SqlCommand("sp_insertstudentdetail", con);
com.CommandType = CommandType.StoredProcedure;
try
{
string filename = string.Empty;
string uniqueFileName = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
string fileExtension = Path.GetExtension(filename).ToLower();
uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName));
}
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + uniqueFileName : string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
}
}
Here is editrow:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (e.CommandName == "EditRow")
{
Image1.ImageUrl = ((System.Web.UI.WebControls.Image)gr.Cells[7].Controls[0]).ImageUrl;
}
}
and here is my output of my screenshot:
http://s3.postimg.org/bpgzjlmub/untitled.jpg
Can anyone help me to fix my issue, I'm new to .net.
Any help would be highly appreciated.
The gridview in asp.net does not automatically update itself. You need to again bind the gridview. What you need to do is put the code of binding the grid in one function say bindgrid() something like this.
public void bindgrid()
{
con = new SqlConnection(connStr);
con.Open();
da = new SqlDataAdapter("select * from Grid_Data", con);
Dataset ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
and then call bindgrid() after every insert and update performed in grid. If this doesn't work out, I might need to see your binding logic.
Thank you
I have been created student details page.
Here is my code for update:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("sp_updatestudentdetail", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
com.Parameters.AddWithValue("#Email", Textemail.Text.Trim());
com.Parameters.AddWithValue("#Mobilenum", Textmobilenum.Text.Trim());
com.Parameters.AddWithValue("#EC_id", Textcurricular.SelectedValue);
try
{
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
string[] files = Directory.GetFiles(Server.MapPath("~/Images"));
foreach (string f in files) File.Delete(f);
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
string fileExtension = Path.GetExtension(filename).ToLower();
string uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName));
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + uniqueFileName : string.Empty);
}
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
The insertion works fine., when i edit the row from gridview and doing some changes and update, the updated row is not working.
After insertion the row in grid view like this: screenshot-1
after edit and update the row same in gridview like this: screenshot-2
so what is my mistake in my update code?
Can anyone guide me to fix this?
Thanks,
I am creating student records using c# and asp .net. For this, I added 5 fields - name, class, section, address and image.
When inserting student1.jpg, it works fine. Problem appears When I insert second record for same name (student1.jpg) with different image. Insertion fails with some error like "image already exists".
After I understood the purpose of GUID, I want to use these for my work.
Is it possible to do so and if yes, can someone help me?
Here is my full code-behind file:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
com.Parameters.AddWithValue("#Image",(filename.Length>0)? "Images/" + filename:string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
string filename = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
if (File.Exists(Server.MapPath("~/Images/" + filename)))
{
Label6.Visible = true;
return;
}
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
com.Parameters.AddWithValue("#Image",(filename.Length>0)? "Images/" + filename:string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
}
Thank you.
Namespace: using System.IO;
For StoredProdure3:
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
string fileExtension = Path.GetExtension(filename).ToLower(); // this will give you file extension.
string uniqueFileName = Guid.NewGuid().ToString() + fileExtension; // this will give you unique filename.
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName)); // save the image with guid name.
com.Parameters.AddWithValue("#Image",(filename.Length > 0) ? "Images/" + uniqueFileName : string.Empty); // now you can save the new filename in database for associated record.
}
For StoredProdure1:
string filename = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
if (File.Exists(Server.MapPath("~/Images/" + filename)))
{
Label6.Visible = true;
return;
}
string fileExtension = Path.GetExtension(filename).ToLower(); // this will give you file extension.
string uniqueFileName = Guid.NewGuid().ToString() + fileExtension; // this will give you unique filename.
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName)); // save the image with guid name.
}
com.Parameters.AddWithValue("#Image",(filename.Length > 0)? "Images/" + uniqueFileName : string.Empty);
com.ExecuteNonQuery();
Now all uploaded images that will be saved to drive will have unique name even if original filename is same but images are different.
Assuming that Id is the primary key on your table, then just replace
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
with
com.Parameters.AddWithValue("#id", System.Guid.NewGuid().ToString());
If this doesn't resolve your issue, I could assist further if you provided the structure of your table, or the code in your stored procedure.
--EDIT--
With your edits, my answer no longer makes sense as we now know that varchar isn't acceptable as id and the error is being thrown at the point of the fileupload.SaveAs().
Suprabhat Biswal is on the right track as you should be using GUID to be changing your file name.
Here's some updated code, NOTE that i changed the id back to the Textid.Text.Trim().
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
var filename = string.Format("{0}.{1}", Guid.NewGuid().ToString(), Path.GetExtension(fileupload.PostedFile.FileName).ToLower());
var full_path = Server.MapPath("~/Images/", filename);
if (fileupload.PostedFile.FileName.Length > 0)
{ ;
fileupload.SaveAs(full_path);
}
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + filename : string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
string filename = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
var filename = string.Format("{0}.{1}", Guid.NewGuid().ToString(), Path.GetExtension(fileupload.PostedFile.FileName).ToLower());
var full_path = Server.MapPath("~/Images/", filename);
// This IF statement should never be hit since we're using GUID for the file name.
if (File.Exists(full_path))
{
Label6.Visible = true;
return;
}
fileupload.SaveAs(full_path);
}
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + filename : string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
}
If i understood your problem:
These changes are enough with your original code for use of GUID.
make change in db table "Student" for column Id from "int" to "NVARCHAR(36)"
Form Code behind Pass "Id" parameter values as
string ID = Guid.NewGuid().ToString();
com.Parameters.AddWithValue("#id", ID);
you can keep image name as original name.
OR------
U can directly genarat GUID in DataBase also as follows
ALTER PROCEDURE StoredProcedure3
(
#Name Varchar (100),
#Class varchar (50),
#Section Varchar (50),
#Address Varchar (50),
#Image Varchar (50)
)
AS
begin
DECLARE #id NVARCHAR(36);
SET #id = NEWID();
Update Student set Name = #Name, Class= #Class, Section= #Section, Address = #Address, Image = #Image where id=#id
End
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to restrict file type in FileUpload control
I have a problem, using my image uploader. It will upload all type of files.
I need code behind, to sort out if it's an image (jpg, png and so on).
Then it needs to save the path and filename in my sql.
Saving name and path is up and running, so is the regular expression. I now need to incorporate som code that i have found here. The question is, how it's done?
My code behind is:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("~/_PublicData/Images/" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Computer_Klubben_CommunitySiteConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string strQuery = "insert into dbo.Billeder (FileName, FilePath)" + " values(#FileName, #FilePath)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#FileName", FileName);
cmd.Parameters.AddWithValue("#FilePath", "~/_PublicData/Images/" + FileName);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
I need to put that code inside the following code, that I have found here.
How can i upload only jpeg files?
Do I place my code after the code from here, or were do I place it?
Please help.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string fileExt =
System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExt == ".jpeg" || fileExt == ".jpg")
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("~/_PublicData/Images/" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Computer_Klubben_CommunitySiteConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string strQuery = "insert into dbo.Billeder (FileName, FilePath)" + " values(#FileName, #FilePath)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#FileName", FileName);
cmd.Parameters.AddWithValue("#FilePath", "~/_PublicData/Images/" + FileName);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
else
{
//Show Error Message. Invalid file.
}
}
}
you have asked from code behing so Try this method to validate your file names if they are some image or not. by comparing their extensions.. Just pass your FileUplaod control's name to this method and validate your Button's Click..
private Boolean ImageUploadValidation(FileUpload UploadedFile)
{
String FileExtension = String.Empty, Code = String.Empty;
try
{
if (String.IsNullOrEmpty(UploadedFile.PostedFile.FileName))
{
Code = "<script> alert(' Please select file');</script>";
ClientScript.RegisterStartupScript(this.GetType(), "someKey", Code);
return false;
}
FileExtension = Path.GetExtension(UploadedFile.FileName).ToLower();
if (!FileExtension.Equals(".gif") &&
!FileExtension.Equals(".png") &&
!FileExtension.Equals(".jpg") &&
!FileExtension.Equals(".bmp") &&
!FileExtension.Equals(".gif") &&
!FileExtension.Equals(".jpeg") &&
!FileExtension.Equals(".tif") &&
!FileExtension.Equals(".tiff"))
{
Code = "<script> alert(' Please select valid file. File can be of extension(gif, png, jpg, bmp, gif, jpeg, tif, tiff)');</script>";
ClientScript.RegisterStartupScript(this.GetType(), "someKey", Code);
return false;
}
return true;
}
catch (Exception)
{
throw;
}
I found a solution with this workaround:
<asp:FileUpload ID="fuImportImage" runat="server" />
<asp:RegularExpressionValidator ID="regexValidator" runat="server"
ControlToValidate="fuImportImage"
ErrorMessage="Only JPEG images are allowed"
ValidationExpression="(.*\.([Jj][Pp][Gg])|.*\.([Jj][Pp][Ee][Gg])$)">
</asp:RegularExpressionValidator>
Here is regex for you..
System.Text.RegularExpressions.Regex imageFilenameRegex = new
System.Text.RegularExpressions.Regex(#"(.*?)\.(jpg|jpeg|png|gif)$",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
bool ismatch =imageFilenameRegex.IsMatch(imgFile.FileName)