ASP.NET clear HttpContext.Current.Request.Files - asp.net

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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}

Related

DownloadFileAsync with webclient issue

I am trying to download file from FTP using Webclient DownloadFileAsync method. i have used below code
private bool DownloadFileFromFtp()
{
try
{
MyWebClient client = new MyWebClient();
Uri ftpurl = new Uri("ftp://MyFtpserver/Filename.pdf");
client.Credentials = new NetworkCredential("Userid", "mypassword");
client.DownloadProgressChanged += Client_DownloadProgressChanged;
client.DownloadDataCompleted += Client_DownloadDataCompleted;
client.DownloadFileAsync(ftpurl, #"D:\RTP\Filename.pdf");
return true;
}
catch (Exception ex)
{
return false;
}
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
lbldatareceived.Text = bytesIn + "/" + totalBytes;
lblPercentage.Text = percentage+"%";
FileProgress.Attributes.CssStyle.Add("width", Convert.ToString(percentage) + '%');
FileProgress.Attributes.Add("aria-valuenow", Convert.ToString(percentage));
}
private void Client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
throw new NotImplementedException();
}
When I run this code file download gets starts and browser start loading. How can I download files without loading a browser?

How to get pathname of image from FileUpload in grid view

Hello i have my FileUpload in gridview.I upload image for every row and then click button called UPLOAD. So that it should get image path from every row and upload. Onclick listener for UPLOAD is UploadBtn_onClick.
Code for UploadBtn_onClick is
protected void UploadBtn_onClick(object sender, EventArgs e)
{
foreach (GridViewRow row in StudentGrid.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
try
{
UpdateEmailProperties objUpdateEmailId = new UpdateEmailProperties();
GridViewRow grdrow = (GridViewRow)((FileUpload)sender).NamingContainer;
FileUpload filename = (FileUpload)grdrow.Cells[5].FindControl("fileuploadimages");
objUpdateEmailId.StudId = int.Parse(row.Cells[6].Text);
objUpdateEmailId.Email = row.Cells[3].Text;
objUpdateEmailId.profilepath = "profilepics/" + filename;
int intStatus;
intStatus = Stud.UpdateStudentEmailId(objUpdateEmailId);
if (intStatus != 0)
{
lblWarning.Text = "Updated successfully";
}
else
{
lblWarning.Text = "Failed to Update";
}
}
catch (Exception ex)
{
//LogFile.CreateLog("User", "AddPlacement", ex.Message);
lblWarning.Text = "Error: " + ex.Message.ToString();
}
}
}
}
But i am getting error as
Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.FileUpload'
.
I need to fetch name of file returned from loadfile

File Upload is not working in asp.net

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

how to clear ASP.net DropDownList show previous selected item

please help me how to recover it. I used ddlHassection.Items.Clear(); but its not working properly.
using (var context = new SMAPPDBEntities())
{
var addDept = new SMDepartment
{
DepartmentCode = txtDeptCode.Text,
DepartmentName = txtDeptName.Text,
UnitID= Convert.ToInt32( ddlUnitName.SelectedValue),
Description = txtDeptDescription.Text,
DepartmentHead = Convert.ToInt32(ddlDeptHeadName.SelectedValue),
HasSection = Convert.ToBoolean(ddlHasSection.SelectedValue),
Tag= txtDeptTag.Text
};
try
{
context.SMDepartment.Add(addDept);
context.SaveChanges();
}
catch (Exception ex)
{
ex.ToString();
}
}
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
DropDownList1.Items.Clear();
}
or
DDL1.ClearSelection();

How to insert image by creating folder in asp.net?

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";
}
}

Resources