Get File Name using Javascript : ASP.NET FileUpload Control

Many of C# developers looking for getting filename at client side.

Following is the solution for that.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="upload.aspx.cs" Inherits="UploadImagePreview.upload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function getFileName() {
var varfile = document.getElementById("FileUploadControl");
document.getElementById("filename").value = varfile.value;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
Select File To Upload
</td>
<td>
<asp:FileUpload ID="FileUploadControl" runat="server" onchange="getFileName()" />
</td>
</tr>
<tr>
<td>
Get FileName Using JavaScript
</td>
<td>
<input type="text" id="filename" />
</td>
</tr>
<tr>

<td colspan="2" align="center">
<asp:Button runat="server" ID="buttonUpload" Text="Upload" OnClick="buttonUpload_Click" />
</td>
</tr>
<tr>
<td>
Upload Status :
</td>
<td>
<asp:Label runat="server" ID="UploadStatus" />
</td>
</tr>
</table>
</form>
</body>
</html>


and code behind is

/**
*  Developed By : Java.Net
* */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace UploadImagePreview
{
public partial class upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void buttonUpload_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
if (FileUploadControl.PostedFile.ContentType == "image/jpeg") // to check file extension
{
if (FileUploadControl.PostedFile.ContentLength < 204800) // to check file size
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
UploadStatus.Text = "File uploaded!";
}
else
UploadStatus.Text = "Cannot Upload file. The file has to be less than 200 kb";
}
else
UploadStatus.Text = "You can upload only .jpg or .jpeg files";
}
catch (Exception ex)
{
UploadStatus.Text = "The file could not be uploaded. Due to Error occured: " + ex.Message;
}
}
}
}
}

6 Responses to Get File Name using Javascript : ASP.NET FileUpload Control

  1. Pingback: URL

  2. Pingback: tahoe power

  3. This is really interesting, You’re a very skilled blogger.
    I’ve joined your rss feed and look forward to seeking more of your great post.
    Also, I have shared your website in my social
    networks!

    Feel free to visit my blog post … how attract girls

  4. My name is Theron. I live in Hengelo, Netherlands. I randomly
    stumble on javadotnet.in. I just want to say “Hi”.

    Here is my website … restaurants near me

  5. Pingback: backlink Site List 2016

  6. Pingback: Tech Updates

Leave a Reply

Your email address will not be published.