File Uploading Using ASP.NET AJAX

Manimaddu
Posted by Manimaddu under ASP.NET AJAX category on | Points: 40 | Views : 837
Hi All..
This code is used to upload a file using ASP.NET AJAX

Create a table for storing files.


CREATE TABLE tbl_FileUpload
(
Id INT PRIMARY KEY IDENTITY,
FileName VARCHAR(50),
Extention VARCHAR(50),
Content VARCHAR(500),
Data VARBINARY(MAX)
)


Create a procedure to insert the files


CREATE PROCEDURE usp_FileUpload
(
@FileName VARCHAR(50),
@Extention VARCHAR(50),
@Content VARCHAR(500),
@Data VARBINARY(MAX)
)
AS
BEGIN
INSERT INTO tbl_FileUpload (FileName,Extention,Content,Data)VALUES(@FileName,@Extention,@Content,@Data)
END


FileUpload.aspx:

Download the AjaxControlToolKit from www.ajaxcontroltoolkit.codeplex.com

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<title></title>
<script type="text/javascript">
function uploadStart(){
document.getElementById('<%=lblUploadMessage.ClientID %>').innerHTML = "";
}
function uploadComplete(){
document.getElementById('<%=lblUploadMessage.ClientID %>').innerHTML = "File Uploaded Successfully";
}
function uploadError(){
AsyncFileUpload1_UploadedError();
document.getElementById('<%=lblUploadMessage.ClientID %>').innerHTML = "File upload Failed.";
}
</script>
</head>
<body>
<form id="form1" runat="server" visible="True">
<asp:ScriptManager ID="sriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="inProgress.gif" width="50" height="50" alt="loading" /></asp:Label>
<br />
<ajax:AsyncFileUpload runat="server" ID="AsyncFileUpload1" Width="218px" CompleteBackColor = "White" OnClientUploadStarted="uploadStart" UploadingBackColor="#CCDDEE" onuploadedcomplete="AsyncFileUpload1_UploadedComplete" ThrobberID="Throbber" OnClientUploadComplete="uploadComplete" OnClientUploadError="uploadError" />
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID="lblUploadMessage" runat="server" SkinID="ErrorMessageLabelStyle"></asp:Label>
<asp:Button ID="btnView" runat="server" Text="View" onclick="btnView_Click" Width="105px" />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate><asp:Label ID="lblId" runat="server" Text='<% #Eval("Id") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Document Name">
<ItemTemplate><asp:Label ID="lblFileName" runat="server" Text='<% #Eval("FileName") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate><asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownLoad" CommandArgument='<%# Eval("FileName") %>'></asp:LinkButton></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>


FileUpload.aspx.cs:


using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;
using AjaxControlToolkit;
using System.IO;

namespace FileUpLoadUsingAjax
{
public partial class FileUpload : System.Web.UI.Page
{
SqlConnection sqlCon = new SqlConnection(WebConfigurationManager.ConnectionStrings["conString3"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack){
fill();
}
}
protected void AsyncFileUpload1_UploadedComplete(object sender, EventArgs e)
{
if (AsyncFileUpload1.HasFile){
string Extension = System.IO.Path.GetExtension(AsyncFileUpload1.FileName);
if (AsyncFileUpload1.PostedFile.ContentLength < 1048576 && Extension.ToLower() == ".docx")
{
try{
if (AsyncFileUpload1.HasFile){
System.Threading.Thread.Sleep(3000);
int size = AsyncFileUpload1.PostedFile.ContentLength;
string filename = Path.GetFileName(AsyncFileUpload1.PostedFile.FileName);
string extension = Path.GetExtension(filename);
string contentType = AsyncFileUpload1.PostedFile.ContentType;
byte[] fileData = new byte[size];
AsyncFileUpload1.PostedFile.InputStream.Read(fileData, 0, size);
sqlCon.Open();
SqlCommand cmd = new SqlCommand("usp_FileUpload", sqlCon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@FileName", filename));
cmd.Parameters.Add(new SqlParameter("@Extention", extension));
cmd.Parameters.Add(new SqlParameter("@Content", contentType));
cmd.Parameters.Add(new SqlParameter("@Data", fileData));
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", "Upload Sucessfully...!", false);
}
}
catch (Exception ex){
lblUploadMessage.Text = "ERROR: " + ex.Message.ToString();
}
}
else{
lblUploadMessage.Text = "Incorrect File Format";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", "InCorrect Format(.Docx and .Doc Only. and Upto 1MB) ;", false);
}
}
}
public void fill(){
sqlCon.Open();
SqlCommand cmd = new SqlCommand("select * from tblFileUpload", sqlCon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
sqlCon.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnView_Click(object sender, EventArgs e)
{
fill();
}
protected void DownLoad(object sender, EventArgs e)
{
string fileName = (sender as LinkButton).CommandArgument;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
}
}
}


Thank You..

Comments or Responses

Login to post response