Creating a file upload feature without jquery or ajax - c#

I have to create a file upload that only allows .csv files. So far, I have a cosmetic interface of:
<asp:Label ID="importLabel" runat="server" Text="Update Prices" CssClass="fieldLabel" />
<asp:FileUpload ID="importFileUpload" runat="server" OnDataBinding="importFileUpload_DataBinding"/>
<asp:Button ID="importFileButton" runat="server" Text="Update Prices" CssClass="fieldlabel" OnClick="importFileButton_Click" />
<br />
<asp:RegularExpressionValidator ID="uploadValidator" runat="server" ControlToValidate="importFileUpload" ErrorMessage="Only .csv files are allowed"
ValidationExpression="(.+\.([Cc][Ss][Vv]))" />
It works as it should where you can select a .csv file, however I'm not sure of my next step here. Any help or any nudge in the right direction would be awesome!

The next step is uploading the selected file from the code behind:
protected void importFileButton_Click(object sender, EventArgs e)
{
if (importFileUpload.HasFile)
{
string fileExt =
System.IO.Path.GetExtension(importFileUpload.FileName);
if (fileExt == ".csv")
{
try
{
importFileUpload.SaveAs("C:\\Uploads\\" + importFileUpload.FileName);
importLabel.Text = "File name: " +
importFileUpload.PostedFile.FileName + "<br>" +
importFileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
importFileUpload.PostedFile.ContentType;
}
catch (Exception ex)
{
importLabel.Text = "ERROR: " + ex.Message.ToString();
}
}
else
importLabel.Text = "Only .csv files allowed!";
}
else
importLabel.Text = "You have not specified a file.";
}

I have used dropzone.js before for this specific purpose. It does not require jquery. You should be able to do something like this below:
Dropzone.options.filedrop = {
acceptedMimeTypes: 'text/csv',
}
See this question on implementation for limiting specific mime types.

Related

How to download File name contains Single quote Special character using ASP.NET C# Web form

In my existing application file name contains Single quote (') Special character EXample file name: Zahed's.doc. When I am trying to download this file I am not able to download because the file name is contained 's .
Below is my uploading design code:
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="textfield_new1" />
My uploading .cs Code:
bo.Para21 = FileUpload1.FileName.ToString();//ResumePath
string FinalFileName = Convert.ToString(Sno) + bo.Para21;
FileUpload1.PostedFile.SaveAs(Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Resumes/" + FinalFileName);
Below is my Downloading file design code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkbtn_ResumeUpload" runat="server" CssClass="cv_heading" OnClick="lnkbtn_ResumeUpload_Click"></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
Button click for Dowloading code:
protected void lnkbtn_ResumeUpload_Click(object sender, EventArgs e)
{
string path = lnkbtn_ResumeUpload.Text;
string ResumePath = System.Configuration.ConfigurationManager.AppSettings["ResumePath"].ToString();
System.Web.UI.ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "SCRIPT", "window.open('"+ResumePath+path + "')", true);
}
My issue is already 800 users are uploaded with the file name 's and I am not able to download that application, how to resolve this type of issue.
Try to encode the filename using HttpUtility.UrlEncode()
https://msdn.microsoft.com/en-us/library/4fkewx0t.aspx
Example:
If your filepath is called "path" you need to encode it first, then send it to javascript.
string filePath = HttpUtility.UrlEncode(path);
System.Web.UI.ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "SCRIPT", "window.open('"+ filePath + "')", true);
Another solution is HttpUtility.JavaScriptStringEncode which encode your javascript string completely that contains apostrophe.
The problem is that the generated javascript will be broken because it will be:
window.open('...Zahed's.doc');
So the '-character will break your script. Easiest solution is to replace ' with " in your code on the window-open part:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "SCRIPT", "window.open(\"" +ResumePath + path + "\")", true);

Checking if file exists in asp.net mvc 5

I am checking for the existence of a file bu cannot find it, regardless of whether it is there or not
if (System.IO.File.Exists("~/files/downloads/" + fileCode + ".pdf"))
{
return File("~/files/downloads/" + fileCode, "application/pdf", Server.UrlEncode(fileCode));
}
else
{
return View("ErrorNotExistsView");
}
How can I amend the code to check for the existence of the file correctly?
System.IO.File will work if you provide an absolute path or a relative path. A relative path will not be relative to the HTML root folder, but the current working directory. The current working directory will be a value like C:\Program Files (x86)\IIS Express.
The ~ character at the beginning of the file path is only interpreted as part of the current ASP.NET context, which the File methods know nothing about.
The method to help you here is HttpServerUtility.MapPath
If you are in a controller method, you can invoke this method on the object HttpContext.Server, otherwise (e.g. in a View) you can use HttpContext.Current.Server.
var relativePath = "~/files/downloads/" + fileCode + ".pdf";
var absolutePath = HttpContext.Server.MapPath(relativePath);
if(System.IO.File.Exists(absolutePath)) ....
Here's my solution:
<span>
#{
var profileImg = "/Images/" + User.Identity.GetUserId() + ".jpg";
var absolutePath = HttpContext.Current.Server.MapPath(profileImg);
if (System.IO.File.Exists(absolutePath))
{
<img alt="image" width="50" height="50" class="img-circle" src="#profileImg" />
}
else
{
<img alt="image" width="50" height="50" class="img-circle" src="~/Images/profile_small.jpg" />
}
}
</span>
Exists() can return false if app has not sufficient permissions to access the file. So you should grant those to appPool on specific folder and files.
File.Exists() will need the full path.
Try using something like:
#"C:\users\yourUsername\myDocuments\files\\downloads\" + fileCode + ".pdf"
instead of:
"~/files/downloads/" + fileCode + ".pdf"
#if (Session["staff_no"] != null)
{
string image = Session["staff_no"].ToString();
if (Session["sex"].ToString() == "1")
{
if (#File.Exists(Server.MapPath("/images/employees/profile_pic/" + image + ".jpg")).ToString() == "True")
{
<img id="prof_image2" src="/images/employees/profile_pic/#Url.Content(Session["staff_no"].ToString() + ".jpg")" onerror="this.src = '/images/employees/profile_pic/profile-pic-male.jpg'" class="img-circle" alt="User Image">
}
else
{
<img id="prof_image2" src="/images/employees/profile_pic/profile-pic-male.jpg" class="img-circle" alt="User Image">
}
}
else
{
if (#File.Exists(Server.MapPath("/images/employees/profile_pic/" + image + ".jpg")).ToString() == "True")
{
<img id="prof_image2" src="/images/employees/profile_pic/#Url.Content(Session["staff_no"].ToString() + ".jpg")" onerror="this.src = '/images/employees/profile_pic/profile-pic-female.jpg'" class="img-circle" alt="User Image">
}
else
{
<img id="prof_image2" src="/images/employees/profile_pic/profile-pic-female.jpg" class="img-circle" alt="User Image">
}
}
}

How optimal the code can be with dynamically adding the controls

In a website I am designing I need to show images which I upload using asp:FileUpload control. So after uploading I am adding div, img and textarea using a string builder and then loading it into panel which I have already created. So is it better to use Stringbuilder to load inner HTML or is it good to use HtmlgenericControls to add the controls like image and textarea. I am using C#. My current coding way is as follows:
Frontend:
<form id="form1" runat="server">
<div class="transbox" id="mainbk" runat="server" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;" >
<asp:FileUpload runat="server" ID="UploadImages" style="background-color:white; position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 350px; right: 251px;" Width="500px" AllowMultiple="true"/>
<asp:Button runat="server" ID="uploadedFile" style="position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 870px; width: 112px; height: 29px;" Text="Upload" OnClick="uploadFile_Click" />
<asp:Panel ID="updtpanel" runat="server" CssClass="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute" Visible="false">
</asp:Panel>
</div>
</form>
and backend is as follows:
protected void uploadFile_Click(object sender, EventArgs e)
{
if (UploadImages.HasFiles)
{
int tid = 0;
string fileExt = Path.GetExtension(UploadImages.FileName).ToLower();
if (fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp")
{
HtmlGenericControl d = new HtmlGenericControl("div");
Button btnsave = new Button();
btnsave.Text = "Save";
sb.Append("<div class=" + "\"savback\"" + ">");
sb.Append("<div class=" + "\"head\"" + ">Write Description</div>");
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
id += 1;
tid = tid + 1;
string textid = "txt" + tid;
filepath = Server.MapPath("~/Images/Gallery/" + uploadedFile.FileName);
uploadedFile.SaveAs(filepath);
newpath = "../Images/Gallery/" + uploadedFile.FileName;
try
{
updtpanel.Visible = true;
sb.Append("<div class=" + "\"dataload\"" + ">");
sb.Append("<img class=" + "\"loadimg\"" + "src=" + "\"" + newpath.ToString() + "\"" + " />");
sb.Append("<textarea class=" + "\"txtdes\"" + "id=" + "\"" + textid + "\"" + "></textarea>");
sb.Append("</div>");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
sb.Append("</div>");
d.InnerHtml = sb.ToString();
updtpanel.Controls.Add(d);
updtpanel.Controls.Add(btnsave);
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select only Image Files!!');", true);
}
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select a File First!!');", true);
}
}
Please let me know which will be the good way of creating dynamic controls??
Optimal code:
Doesn't contain more than 50 lines of difficult to read code (agreed, it's not unreadable, but still, minor refactoring would help),
Doesn't mix CSS with HTML, together with presentation-related HTML attributes such as width,
Doesn't use the JavaScript alert.
Let's get back to your question. Which one is better: StringBuilder or HtmlGenericControl?
Better being an extremely vague term, let's answer a bunch of slightly different questions:
Which one is faster ?
Probably StringBuilder, given that it doesn't matter. At all. Compared to the time spent downloading an image (say two seconds, i.e. 2 000 ms.), the comparison in performance between StringBuilder and HtmlGenericControl will be very probably less than a millisecond. Is it important that you waste 1 ms. on a process which takes 2 000 ms.?
Which one is safer ?
How many errors do you spot in the following code?
sb.Append("<div class=\"illustration\"><span-class=\"contents\">")
.Append("<img class=" + "\"loadimg\"" + "srv=" + "\"" + newpath + "\"" + ">")
.Append("/div></span>");
Let's see:
div and span are inverted,
the closing div is missing the '<' character,
img is missing '/' (if the output is XHTML),
there is a typo in src written as srv,
span-class should have been span class,
there is no space before src (srv).
Nearly every of those mistakes could have been easily avoided by letting .NET Framework the task of generating HTML from strongly typed objects.
Which one is more readable ?
IMO, neither. HTML code can be written in a clean way, making it extremely readable. In the same way, it would be easy to be lost in all those calls to embedded controls if the code is a piece of crap.
Which one is more reliable ?
.NET Framework is assumed to be heavily tested and particularly reliable, at least compared to average business applications. The more you confide to .NET Framework, the better, unless you know how to do better and you've tested your approach, submitted it for pair reviews, etc.
In the case of StringBuilder, you can hardly unit-test your code. Letting .NET Framework do the HTML generation in your place means that you can concentrate more on the actual objects you manipulate, and testing them is slightly easier.
So, what is the single best solution ?
Personally, if I were stick with classical ASP.NET (by contrast to ASP.NET MVC), I would create a dedicated control with an HTML template.
If for some reasons, this is not possible, then pick HtmlGenericControl: it abstracts the HTML and let you concentrate on the objects themselves.
If you had a requirement to write clean, readable HTML code, HtmlGenericControl would be a burden, and you would have to pick string concatenation or some templating system. ASP.NET controls are known for generating not-so-good HTML code. Given the HTML code in your question, this limitation doesn't apply to your case.

AJAX javascript not firing asp.net c#

When I add new controls to my web application, the javascript does not fire. I've tried many solutions, but none of them work. Specifically, the accordion/accordion pane from the AJAX Control Toolkit does not slide up/down. Also the FileUploadProgress control from Obout uses javascript functions which do not fire. If I open a new web application project and try all this, it works just fine. My project is quite large so I cannot start from scratch. Can someone please tell me what could be wrong with my project? I have no errors. The javascript simply does not fire. Please help. I am using asp.net c#.
EDIT:
Here is the code for file upload progress control. I do have alert statements but they do not fire.
<script type="text/JavaScript">
function Clear() {
alert("here1");
document.getElementById("<%= uploadedFiles.ClientID %>").innerHTML = "";
}
function ClearedFiles(fileNames) {
alert("here2");
alert("Cleared files with bad extensions:\n\n" + fileNames);
}
function Rejected(fileName, size, maxSize) {
alert("here3");
alert("File " + fileName + " is rejected \nIts size (" + size + " bytes) exceeds " + maxSize + " bytes");
}
</script>
<input type="file" name="myFile1" runat="server"/><br/>
<input type="file" name="myFile2" runat="server"/><br/>
<input type="file" name="myFile3" runat="server"/><br/>
<input type="submit" value="submit" name="mySubmit" /><br/>
<br/>
<fup:FileUploadProgress ID="FileUploadProgress1"
OnClientProgressStopped = "function(){alert('Files are uploaded to server');}"
OnClientProgressStarted = "Clear"
ShowUploadedFiles = "true"
OnClientFileRejected = "Rejected"
OnClientFileCleared = "ClearedFiles"
runat = "server"
>
<AllowedFileFormats>
<fup:Format Ext="gif" MaxByteSize="10240"/>
<fup:Format Ext="jpg" MaxByteSize="10240"/>
<fup:Format Ext="jpeg" MaxByteSize="10240"/>
<fup:Format Ext="png" MaxByteSize="10240"/>
</AllowedFileFormats>
</fup:FileUploadProgress>
<asp:Label runat="server" id="uploadedFiles" Text="" />
And here's the code-behind for it:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
HttpFileCollection files = Page.Request.Files;
uploadedFiles.Text = "";
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (file.FileName.Length > 0)
{
if (uploadedFiles.Text.Length == 0)
uploadedFiles.Text += "<b>Successfully uploaded files: </b><table border=0 cellspacing=0>";
uploadedFiles.Text += "<tr><td class='option2'>" + file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1) + "</td><td style='font:11px Verdana;'> " + file.ContentLength.ToString() + " bytes</td></tr>";
}
}
if (uploadedFiles.Text.Length == 0)
uploadedFiles.Text = "no files";
else
uploadedFiles.Text += "</table>";
}
}
Thanks in advance!!
Looks like it is because you are passing anything to your javascript functions. :
Here is what you have. :
OnClientProgressStarted = "Clear"
ShowUploadedFiles = "true"
OnClientFileRejected = "Rejected"
OnClientFileCleared = "ClearedFiles"
Here is what I think you should probably have. :
OnClientProgressStarted = "Clear();"
ShowUploadedFiles = "true"
OnClientFileRejected = "Rejected();"
OnClientFileCleared = "ClearedFiles();"
Also, several of those functions require parameters, which I did not list above......Hopefully this helps you.

Getting the new filename of a file saved with ajax AsyncFileUpload?

I'm saving a file with the asyncfileupload ajax plugin from the ajax toolkit and when I save it I'm changing the filename (to avoid multiple files with the same name).
After the file is uploaded, the user needs to know what the file has been named so I'm using this javascript code on the onclientuploadcomplete event.
function UploadComplete(sender, args) {
alert(args.get_fileName());
}
This works except it gets the old name, not the new name (which is determined server-side). Is there any way to get it to return the new name rather than the old name? Or any work around to achieve this?
This is my code in the code behind the get the new filename:
string filename = DateTime.Now.ToString("dMyHmsf") + e.filename;
string strPath = MapPath("~/SavedImages/") + filename;
AsyncFileUpload1.SaveAs(strPath);
I got the answer from http://forums.asp.net/post/4139037.aspx It works for me...
copied code from there:
<asp:ToolkitScriptManager runat="server">
</asp:ToolkitScriptManager>
<!--This script snippet must be located below the ScriptManager-->
<script type="text/javascript">
Sys.Extended.UI.AsyncFileUpload.prototype.newFileName = null; //I did not use this line
function uploadcomplete(sender, e) {
alert(sender.newFileName);
}
</script>
<asp:AsyncFileUpload ID="AsyncFileUpload1" OnClientUploadComplete="uploadcomplete"
runat="server" OnUploadedComplete="AsyncFileUpload1_UploadedComplete1" />
the code behind:
protected void AsyncFileUpload1_UploadedComplete1(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this,
this.GetType(), "newfile",
"window.parent.$find('" + AsyncFileUpload1.ClientID + "').newFileName='newfile.jpg';", true);
}
How about writing the filename to a hiddenfield in the codebehind and the reading that value in your clientside code?

Categories

Resources