how to set value of session on .ashx file in asp.net? - asp.net

I'm using "jquery.uploadify.js" in my website and this jquery uses an ashx file for uploading images into a folder. In the .ashx, i am using Session["FileNameNews"] for saving images name and i am empty my Session["FileNameNews"] at the beginning of my code. But when i uploading two or three or ... images, each time my Session["FileNameNews"] is empty. I do not want to be empty my session every time I upload a photo and i want the uploaded images to be displayed in a listbox of the parent .aspx page. Other means, i need to my session empty in start of uplaod and fill with images names in end of upload. I am able to upload multiple image at a time.
Does anyone have an idea? Please Help me.
Thank you.
.aspx page:
<script type = "text/javascript">
$(window).load(
function() {
$("#<%=FileUpload1.ClientID%>").fileUpload({
'uploader': 'scripts/uploader.swf',
'cancelImg': 'images/cancel.png',
'buttonText': 'Browse Files',
'script': 'Upload.ashx',
'folder': 'Temp',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'multi': true,
'auto': false
});
}
);
</script>
Start Upload
|Clear
<div style = "padding:40px">
<asp:FileUpload ID="FileUpload1" runat="server" />
</div>
and Upload.ashx:
public class Upload : IHttpHandler, IRequiresSessionState {
public void ProcessRequest(HttpContext context)
{
context.Session["FileNameNews"] = "";
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
try
{
HttpPostedFile postedFile = context.Request.Files["Filedata"];
string savepath = "";
string tempPath = "";
tempPath = "Temp";//System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
savepath = context.Server.MapPath(tempPath);
string filename = postedFile.FileName;
if (!Directory.Exists(savepath))
Directory.CreateDirectory(savepath);
string SitePath = context.Server.MapPath(context.Request.ApplicationPath) + #"\Temp\";
string SitePath1 = context.Server.MapPath(context.Request.ApplicationPath) + #"\WebImages\NewsImages\";
string FileN = SitePath + filename + "{---}" + context.Session["UserID"].ToString();
if ((File.Exists(SitePath + filename + "{---}" + context.Session["UserID"])) || (File.Exists(SitePath1 + filename)))
{
return;
}
else
{
postedFile.SaveAs(savepath + #"\" + filename);
postedFile.SaveAs(savepath + #"\" + filename + "{---}" + context.Session["UserID"]);
if (context.Session["FileNameNews"] == "") { context.Session["FileNameNews"] = filename; }
else { context.Session["FileNameNews"] = context.Session["FileNameNews"] + "," + filename; }
context.Response.Write(tempPath + "/" + filename);
context.Response.StatusCode = 200;
}
}
catch (Exception ex)
{
context.Response.Write("Error: " + ex.Message);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

If this ashx handler is the endpoint for your file upload ajax request, and you throw an exception, you will never see the error message from your try / catch. You are likely "swallowing" your exceptions. Drop the try / catch and examine the result status (or error message) using the debug tools in your browser.

Related

MVC UPLOAD IMAGE SAVE IN SQL using ado.net with update (i edit any text box . the image disappear)

[HttpPost]
public ActionResult Create(Showroom showroom)
{
objShowroom.InsertShowroomDetails(showroom);
return RedirectToAction("Index");
}
I had separate data access layer
how to update the upload image in database
insert query no problem with that
if I edit any textbox image will disappear in postback or roundtrip
5. I will use not entity framework so I want to connect with model using ado.net
model folder:
public int UpdateShowroomDetails(Showroom objShowroom)
{
sqlCommandText = "Update Showroom Set CARIMAGE='" + objShowroom.CARIMAGE + "', CARNAME='" + objShowroom.CARNAME + "', CARBRAND='" + objShowroom.CARBRAND + "', PRICE=" + objShowroom.PRICE + " Where ID="+objShowroom.ID ;
return objDAL.ExecuteNonQuery(sqlCommandText);
}
Here is how i save d my image to db using ado.net . Hope this will help you
string fileName = string.Empty;
string servr_path = string.Empty;
string serviceId = string.Empty;
string planId = string.Empty;
if (IdProofFile.HasFile && IdProofFile.PostedFile.FileName != "")
{
string fileType = IdProofFile.PostedFile.ContentType;
if (fileType == "image/jpg" || fileType == "image/jpeg" || fileType == "image/png" || fileType == "image/gif")
{
int fileSize = IdProofFile.PostedFile.ContentLength;
if (fileSize <= 2097152)
{
//fileName = System.IO.Path.GetFileName(IdProofFile.PostedFile.FileName);
fileName = "ID-" + txt_FirstName.Text + "_" + txt_LstName.Text + DateTime.Now.ToString("ddmmyy_hhMMss") + Path.GetExtension(IdProofFile.PostedFile.FileName);
string serverFolder = Server.MapPath("idProof//");
if (!System.IO.Directory.Exists(serverFolder))
{
System.IO.Directory.CreateDirectory(serverFolder);
}
servr_path = serverFolder + fileName;
foreach (int i in ddlservices.GetSelectedIndices())
{
serviceId += "," + ddlservices.Items[i].Value;
}
IdProofFile.SaveAs(servr_path);
}
}
else
{
}
}
else
{
}
}
else
{
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "mask();", true);
mpepopup.Show();
lblMsg.Text = "Min File Size Must Be Greater Than 5 KB and Less Than 2 MB";
}
}
else
{
mpepopup.Show();
// ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "mask();", true);
lblMsg.Visible = true;
lblMsg.Text = "Please upload an image of *.jpg/*.jpeg/*.png/*.gif/*.bmp file type only!!!";
}
}
else
{
mpepopup.Show();
lblMsg.Text = "ID Proof File Not Selected.";
}

Change file name of FILE UPLOAD control

This is my code:
if (FileUpload1.HasFile)
{
try
{
string file_name = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/FoodImage/1/") + file_name);
Label1.Text = "File Upload";
}
catch(Exception)
{
Label1.Text = "Can not Upload File!";
}
}
that code browse the for example "logo.jpg" and save in my server,but i want before to save change the file name,for example Browse button press and choose "logo.jpg" and click open then change the main file name "logo.jpg" to "L1.jpg" and save.
Try this:
//Check if user has selected a file and the file size is not 0
if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)
{
//Set the name you want for the file with no file extension
string newFilename = "L1";
//Get the file extension of the file being uploaded.
string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
//Combine the new filename and the extension. You want to make sure it's the same file extension.
string updatedFilename = newFilename + fileExtension;
//Set the upload location
string SaveLocation = Server.MapPath("~/FoodImage/1/");
bool hasErrors = false;
try
{
//Save the file to location with new filename
FileUpload1.SaveAs(Path.Combine(SaveLocation + updatedFilename));
hasErrors = false;
}
catch (Exception ex)
{
//Display error if any
lblUploadStatus.Text = "Error uploading file. " + ex.Message.ToString();
lblUploadStatus.ForeColor = System.Drawing.Color.Red;
lblUploadStatus.Visible = true;
hasErrors = true;
}
finally
{
//Do something or display success or failure
if (hasErrors == false)
{
lblUploadStatus.Text = "File sucessfully uploaded with new filename: " + updatedFilename;
lblUploadStatus.ForeColor = System.Drawing.Color.Green;
lblUploadStatus.Visible = true;
}
}
}
asp:FileUpload gets rendered as input type="file" and it does not have that option. You can however do this simple workaround. That is, place a textbox below the FileUpload and prompt the user to enter the desired file name there.

asp.net upload control is not working in ipad

The asp.net upload control is uploading the file for first time in Ipad but not after that and not even showing any error
The code is as below
protected void UploadThisFile(FileUpload upload)
{
try
{
string folderpath = ConfigurationManager.AppSettings["BTCommDynamic"].ToString() + ConfigurationManager.AppSettings["Attachments"].ToString();
Guid fileguid = Guid.NewGuid();
string filename = fileguid + upload.FileName;
if (upload.HasFile && dtFiles != null)
{
DataRow drFileRow = dtFiles.NewRow();
drFileRow["FileName"] = upload.FileName;
string theFileName = Path.Combine(Server.MapPath(folderpath), filename);
string theFileName1 = Path.Combine(folderpath, filename);
//string theFileName = folderpath;
//to save the file in specified path
upload.SaveAs(theFileName);
drFileRow["FilePath"] = theFileName1;
double Filesize = (upload.FileContent.Length);
if (Filesize > 1024)
{
drFileRow["FileSize"] = (upload.FileContent.Length / 1024).ToString() + " KB";
}
else
{
drFileRow["FileSize"] = (upload.FileContent.Length).ToString() + " Bytes";
}
dtFiles.Rows.Add(drFileRow);
gvAttachment.DataSource = dtFiles;
gvAttachment.DataBind();
}
}
catch (Exception ex)
{
string message = Utility.GetExceptionMessage(ex.GetType().ToString(), ex.Message);
Display_Message(message);
}
}
Do you use firebug? There might be an error on a client side that prevents the work of your functionality.
Do you have any logic on your client side? Some kinda jquery/ajax calls?

Browse and upload file

I have a ASP.NET (.NET Framework 3.5) Application. Now, I have to place a Button on a aspx-Page with the fallowing functionality on click:
Ask the user for a file with Extension xls (OpenFileDialog)
Upload the selected file to a specific folder on the WebServer
How can I do this?
Thanks for your help.
Here is the code that can be used for file upload after checking certain file types.
protected void Upload_File() {
bool correctExtension = false;
if (FileUpload1.HasFile) {
string fileName = FileUpload1.PostedFile.FileName;
string fileExtension = Path.GetExtension(fileName).ToLower();
string[] extensionsAllowed = {".xls", ".docx", ".txt"};
for (int i = 0; i < extensionsAllowed.Length; i++) {
if (fileExtension == extensionsAllowed[i]) {
correctExtension = true;
}
}
if (correctExtension) {
try {
string fileSavePath = Server.MapPath("~/Files/");
FileUpload1.PostedFile.SaveAs(fileSavePath + fileName);
Label1.Text = "File successfully uploaded";
}
catch (Exception ex) {
Label1.Text = "Unable to upload file";
}
}
else {
Label1.Text = "File extension " + fileExtension + " is not allowed";
}
}
}
You should start with the ASP.NET FileUpload control. Here is a pretty good tutorial on how to complete this task.

How to change fileupload name

im using following code to upload
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~upload/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
I want to change the upload file name...I have to assign file name for every uploaded file how?
This line pickes up the the name of the uploaded file:
string filename = Path.GetFileName(FileUploadControl.FileName);
This line tells the server what to save the file as:
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
Simply change the value of filename to something else before saving.
there is a way to change the name of the file that we downloaded to our "~Server/Userfolder"(as an example)..
i was really thinking on renaming file before the .SaveAs command, which is gonna be like:
if (Request.Files != null)
{
var getmyfile = Request.Files["some_photo"];
try
{
if (getmyfile.FileName != "" && getmyfile.FileName != null && getmyfile.ContentLength > 0)
{
///Create Useruploads path.
var path = Server.MapPath("~/Useruploads" + "\\");
///Get file info that we gonna upload to server..
FileInfo TheFile = new FileInfo(path + Path.GetFileName(getmyfile.FileName));
///Note: i used Path.GetFileName(getmyfile.FileName) code cause getmyfile.FileName gives full path of that file..
if (TheFile.Exists)
{
///Seperate file name and extention..
var fname = Path.GetFileNameWithoutExtension(TheFile.Name);
var ext = TheFile.Extension;
var path2 = path + fname;
///As long as we got file names, same as in server..
while(new FileInfo(path2+ext).Exists)
{
///Add "-img" to its name..
path2 = path2 + "-img";
}
FileInfo ccc = new FileInfo(path2 + ext);
string f_art = ccc.Name.Replace(" ", "");///Clean space.. (Optional)
getmyfile.SaveAs(f_art);
somedb.some_photo = Path.GetFileName(f_art); ///Its not fart its file art lol!
}
else ///if file is not exist in our server..
{
var path3 = (path + Path.GetFileName(getmyfile.FileName));
FileInfo ccc = new FileInfo(path3);
string f_art = ccc.Name.Replace(" ", "");
getmyfile.SaveAs(f_art);
some.some_photo = Path.GetFileName(f_art);
}
}
}
catch(FileNotFoundException ex)
{
form.Set("lblStatus",ex.Message);
}
catch (Exception ex)
{
form.Set("lblStatus", ex.Message);
}
db.somedbs.InsertOnSubmit(somedb);
db.SubmitChanges();
return RedirectToAction("Index");
}
(Optional) Also u can use :
var f_art = System.Text.RegularExpressions.Regex.Replace(Path.GetFileNameWithoutExtension(TheFile.Name), "[^a-zA-Z]", "");
instead of using .Replace(" ",""); but at this it just cleans spaced areas and if u use the code up there its gonna clean everything except A to Z , a to z characters which means no numbers will be applied to that name nor space or other characters which are not between A and Z..

Resources