I need to create a folder within another folder(total 2 folders), in that I need to insert the image.
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
AjaxControlToolkit.AsyncFileUpload async = (AjaxControlToolkit.AsyncFileUpload)sender;
if (async.HasFile)
{
if (image1 != null)
{
try
{
File.Delete(MapPath("~/images/" + SelectHotels.SelectedItem) + image1);
}
catch
{
}
}
image1 = e.FileName;
if (File.Exists(MapPath("~/images/" + SelectHotels.SelectedItem + "/") + image1))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Change Image", "alert('Image with same name already exit please change name and upload');", true);
image1 = null;
}
else
{
if (!Directory.Exists(Server.MapPath("~/images/" + SelectHotels.SelectedItem)))
{
Directory.CreateDirectory(Server.MapPath("~/images/" + SelectHotels.SelectedItem)+image1);
str = "~/images/" + SelectHotels.SelectedItem;
str1 = "~/images/" + SelectHotels.SelectedItem + "/" + image1;
}
Please try this code,
public void EnsureDirectoriesExist()
{
// if the \pix directory doesn't exist - create it.
if (!System.IO.Directory.Exists(Server.MapPath(#"~/Folder_Name/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(#"~/Folder_Name/"));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".jpg")
{
// create posted file
// make sure we have a place for the file in the directory structure
EnsureDirectoriesExist();
String filePath = Server.MapPath(#"~/Folder_Name/" + FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
}
else
{
lblMessage.Text = "Not a jpg file";
}
}
Related
I'm trying to upload a file using FileUpload, and it doesn't work. After I click the button, it reloads the page, but the image is not saved
Below code is from microsoft, but still not working
protected void uploadBtn_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
String path = Server.MapPath("~/Sources/images/");
if (imageUpload.HasFile)
{
String fileExtension =
System.IO.Path.GetExtension(imageUpload.FileName).ToLower();
String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
imageUpload.PostedFile.SaveAs(path
+ imageUpload.FileName);
statusUploadLbl.Text = "File uploaded!";
}
catch (Exception ex)
{
statusUploadLbl.Text = "File could not be uploaded.";
}
}
else
{
statusUploadLbl.Text = "Cannot accept files of this type.";
}
}
Please help, thanks
I want to delete folders and its content created 3 months back...........
i have written a code.....but not working when condition is given
protected void Button1_Click(object sender, EventArgs e)
{
string NewDirectory = "C:\\New Foouterlder\\delete";
DeleteDirectoryIfExist(NewDirectory);
}
private void DeleteDirectoryIfExist(string NewDirectory)
{
DirectoryInfo di = new DirectoryInfo("C:\\New Foouterlder\\delete");
try
{
if (System.IO.Directory.Exists(NewDirectory))
{
if (di.CreationTime< DateTime.Now.AddMonths(-3))
{
Response.Write(MydateTime);
Directory.Delete(NewDirectory, true);
}
else
{
Label1.Text = "Directory Not Exist";
}
}
Response.Write(di.CreationTime);
}
catch (IOException _err)
{
Response.Write(_err.Message);
}
}
}
}
di.CreationTime as 1/1/1601 5:30:00 AM ....why
How can I clear the HttpContext.Current.Request.Files list?
After the postback, this still contains the files.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
this.SaveImages();
}
private Boolean SaveImages()
{
//loop through the files uploaded
HttpFileCollection _files = HttpContext.Current.Request.Files;
//Message to the user
StringBuilder _message = new StringBuilder("Files Uploaded:<br>");
try
{
for (Int32 _iFile = 0; _iFile < _files.Count; _iFile++)
{
if (!string.IsNullOrEmpty(_files[_iFile].FileName))
{
// Check to make sure the uploaded file is a jpg or gif
HttpPostedFile _postedFile = _files[_iFile];
string _fileName = Path.GetFileName(_postedFile.FileName);
string _fileExtension = Path.GetExtension(_fileName);
//Save File to the proper directory
_postedFile.SaveAs(HttpContext.Current.Request.MapPath("files/") + _fileName);
_message.Append(_fileName + "<BR>");
}
}
lblFiles.Text = _message.ToString();
return true;
}
catch (Exception Ex)
{
lblFiles.Text = Ex.Message;
//Refill images in control????
return false;
}
finally
{
//Clear HttpContext.Current.Request.Files!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
I have a problem while writting event for ImageUpload User control.
I want to add a event that fire on imagebutton click in this case that green ok button. I write some code for event but it get raised on pageload() and on postback, so it causes a problem --> Image path which is provided for image upload is get clear after image upload but on a page refresh a same image is upload again and again on every page refresh.
User Control Code
public partial class Gallery_Controls_ImgUpload : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }
public string TxtDesc
{
get {return txtimgdesc.Text;}
set { txtimgdesc.Text = value; }
}
public string TxtImgName
{
get { return txtimgname.Text; }
set { txtimgname.Text = value; }
}
public FileUpload ImgUpld
{
get { return ImgUpload; }
//set { ImgUpload = value; }
}
public string ImgAttr
{
get { return ImgUpload.Attributes["onchange"]; }
set { ImgUpload.Attributes["onchange"] = value; }
}
public event EventHandler ImgBtnUpClick;
protected void imgbtnok_Click(object sender,EventArgs e)
{
ImgBtnUpClick(ImgUpload, e);
}
Code for Adding control in page and upload a file
public partial class Gallery_iupload : System.Web.UI.Page
{
ASP.gallery_controls_imgupload_ascx upctrl;
protected void Page_Load(object sender, EventArgs e)
{
upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
protected void Upload(object sender, EventArgs e)
{
TextBox txtbximgname = (TextBox)upctrl.FindControl("txtimgname");
TextBox txtbxdesc = (TextBox)upctrl.FindControl("txtimgdesc");
FileUpload Imgload = (FileUpload)sender;
if (Imgload.HasFile)
try{
Imgload.SaveAs("C:\\Uploads\\" + txtbximgname.Text + ".jpg");
Label1.Text = "File name: " + Imgload.PostedFile.FileName + "<br>" +
Imgload.PostedFile.ContentLength + " kb<br>" +"Content type: " +
Imgload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
}
you have to put a IsPostBack check in your page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{ upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
}
I keep getting the following error and I don't know how to fix it. Any help would be great please
Exception Details:NullReferenceException was unhandled by users code: Object reference not set to an instance of an object.
protected void LbUpload_Click(object sender, EventArgs e)
{
ERROR: if(FileUpload.PostedFile.FileName == string.Empty)
{
LabelMsg.Visible = true;
return;
}
else
{
string[] FileExt = FileUpload.FileName.Split('.');
string FileEx = FileExt[FileExt.Length - 1];
if (FileEx.ToLower() == "csv")
{
FileUpload.SaveAs(Server.MapPath("CSVLoad//" + FileUpload.FileName));
}
else
{
LabelMsg.Visible = true;
return;
}
}
CSVReader reader = new CSVReader(FileUpload.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
dt.Columns.Add(strHeader);
string[] data;
while ((data = reader.GetCSVLine()) != null)
dt.Rows.Add(data);
GridView1.DataSource = dt;
GridView1.DataBind();
if (FileUpload.HasFile)
try
{
FileUpload.SaveAs(Server.MapPath("confirm//") +
FileUpload.FileName);
LabelGrid.Text = "File name: " +
FileUpload.PostedFile.FileName + "<br>" +
FileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload.PostedFile.ContentType + "<br><b>Uploaded Successfully";
}
catch (Exception ex)
{
LabelGrid.Text = "ERROR: " + ex.Message.ToString();
}
else
{
LabelGrid.Text = "You have not specified a file.";
}
File.Delete(Server.MapPath("confirm//" + FileUpload.FileName));
}
You are checking if the FileName is string.Empty, it sounds like you want to detect when the user clicked the button without selecting a file.
If that happens, the actual PostedFile property will be null (remember, the user didn't posted a file), you should use the FileUpload.HasFile property for that purpose:
protected void LbUpload_Click(object sender, EventArgs e)
{
if(FileUpload.HasFile)
{
LabelMsg.Visible = true;
return;
}
// ...
}
But I would recommend you also to add a RequiredFieldValidator.
More on validation:
Validating ASP.NET Server Controls
ASP.NET Validation in Depth
Are you sure that FileUpload and FileUpload.PostedFile is not null?
Either FileUpload or its PostedFile property must be null.