Showing posts with label FileUpload. Show all posts
Showing posts with label FileUpload. Show all posts
0

AjaxFileUpload AsyncFileUpload In ModalPopUp Extender Asp.Net

This example shows how to use AjaxFileUpload Control Or AsyncFileUpload In ModalPopUp Extender Using C# VB Asp.Net.

Place ToolkitScriptManager and a button inside UpdatePanel on the page, we will open ModalPopup in click event of this button to upload files.

Create one panel on the page and add AjaxFileUpload or Ajax AsyncFileUpload in it.

Async Ajax FileUpload In ModalPopUp Extender


HTML Source
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnUpload" runat="server" 
            Text="Upload File" onclick="btnUpload_Click"/>
            
<asp:ModalPopupExtender runat="server" 
                        ID="modelPopupExtender1" 
                        TargetControlID="btnUpload"
                        PopupControlID="popUpPanel" 
                        OkControlID="btOK" 
                        BackgroundCssClass="modalBackground">
</asp:ModalPopupExtender>
 
 <asp:Panel ID="popUpPanel" runat="server" CssClass="pnl">
 <div style="font-weight: bold; border: Solid 3px Aqua; 
                                background-color: AliceBlue">
 
 <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" 
                     OnUploadComplete="UploadComplete" 
                     OnClientUploadComplete="Success" 
                     ThrobberID="loader" Width="400px"/>
 <asp:Image ID="loader" runat="server" 
            ImageUrl ="~/loading.gif" 
            Style="display:None"/>
 </div><br /><br />
 <asp:Label ID="lblMessage" runat="server"/><br /><br />
 <asp:Button ID="btOK" runat="server" Text="OK" />
 <asp:LinkButton ID="LinkButton1" runat="server" CssClass="close" 
 OnClientClick="$find('modelPopupExtender1').hide(); return false;"/>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>


If you are using AsyncFileUpload Control then don't forget to set UploaderStyle property to Traditional, other wise it will throw invalid argument error.

<ajax:AsyncFileUpload ID="AsyncFileUpload1" runat="server" 
                      UploadingBackColor="Blue" 
                      CompleteBackColor="WhiteSmoke"
                      OnUploadedComplete="SaveUploadedFile" 
                      OnClientUploadComplete="Success" 
                      OnClientUploadError="Error"
                      UploaderStyle="Traditional"/>


Add following Javascript and CSS in head section of page.



Write following code in OnUploadComplete event to save file on server.

protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }


Build and run the code.

Download Sample Code


7

Asp.Net AjaxFileUpload Control With Drag Drop And Progress Bar

This Example explains how to use AjaxFileUpload Control With Drag Drop And Progress Bar Functionality In Asp.Net 2.0 3.5 4.0 C# And VB.NET.

May 2012 release of AjaxControlToolkit includes a new AjaxFileUpload Control which supports Multiple File Upload, Progress Bar and Drag And Drop functionality.

These new features are supported by Google Chrome version 16+, Firefox 8+ , Safari 5+ and Internet explorer 10 + , IE9 or earlier does not support this feature.

AjaxFileUpload Control Example with Drag Drop And Progress Bar

To start with it, download and put latest AjaxControlToolkit.dll in Bin folder of application, Place ToolkitScriptManager and AjaxFileUpload on the page.

HTML SOURCE
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
          
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" 
                    OnUploadComplete="UploadComplete" 
                    ThrobberID="loader"/>
 
<asp:Image ID="loader" runat="server" 
           ImageUrl ="~/loading.gif" Style="display:None"/>


ThrobberID is used to display loading image instead of progress bar in unsupported browsers.

Type of files uploaded can be restricted by using AllowedFileTypes property with comma separated list such as "zip,doc,pdf".

Write following code in OnUploadComplete event to save the file.

C#
protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }
VB.NET
protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }
Build and run the code.

Download Sample Code


3

Asynchronous Multiple File Upload With JQuery Uploadify Asp.Net

This post shows how to use Multiple Asynchronous FileUpload With JQuery Uploadify Example In Asp.Net To Upload Files Asynchronously In Gmail Style With Progress Bar In Asp.Net C# and VB.

Download Latest JQuery Library And Uploadify Plugin.

Create a folder in application and add swf,css and js files in it from links above.

Open HTML source and add reference to these javascripts in head section.

<link href="Scripts/uploadify.css" rel="stylesheet" type="text/css"/>
<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"/> 
<script src="Scripts/jquery.uploadify-3.1.js" type="text/javascript"/>
<script src="Scripts/jquery.uploadify-3.1.min.js" type="text/javascript"/>

Place one FileUpload Control on the page.

   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <asp:FileUpload ID="FileUpload1" runat="server"/>
   4:  </div>
   5:  </form>

Add this JavaScript in Head section.

   1:  <script type = "text/javascript">
   2:  $(document).ready(function() 
   3:  {
   4:    $("#<%=FileUpload1.ClientID %>").uploadify(
   5:    {
   6:      'swf': 'Scripts/uploadify.swf',
   7:      'uploader': 'Handler.ashx',
   8:      'auto': true,
   9:      'multi': true,
  10:      'buttonText': 'Select File(s)'
  11:     });
  12:  });
  13:  </script> 

Right Click on Solution explorer, Add new Generic Handler and write below mentioned code to save the file.

C# CODE
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        HttpPostedFile fileToUpload = context.Request.Files["Filedata"];
        string pathToSave = HttpContext.Current.Server.MapPath("~/Files/") + fileToUpload.FileName;
        fileToUpload.SaveAs(pathToSave);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

VB.NET CODE
Imports System.Web

Public Class Handler
 Implements IHttpHandler

 Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
  Dim fileToUpload As HttpPostedFile = context.Request.Files("Filedata")
  Dim pathToSave As String = HttpContext.Current.Server.MapPath("~/Files/") & fileToUpload.FileName
  fileToUpload.SaveAs(pathToSave)
 End Sub

 Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
  Get
   Return False
  End Get
 End Property
End Class

Build and run the application.

Upload multiple Files Asynchronously With Jquery Uploadify in asp.net

Download Sample Code


1

Upload Multiple Files With FileUpload Or JQuery In Asp.Net

This Example explains How To Upload Multiples Files With FileUpload Or JQuery In Asp.Net.

I have placed four FileUpload Controls and one button on page, Code to save uploaded files to server is written in Click Event of Button.

Download JQuery.js and jQuery.MultiFile.js from JQuery multiple-file-upload plugin site.

Default File size limit is 4 mb but we can upload large files by changing configuration in web.config.

HTML SOURCE OF PAGE
   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <asp:FileUpload ID="FileUpload1" runat="server" />
   4:  <br />
   5:  <asp:FileUpload ID="FileUpload2" runat="server" />
   6:  <br />
   7:  <asp:FileUpload ID="FileUpload3" runat="server" />
   8:  <br />
   9:  <asp:FileUpload ID="FileUpload4" runat="server" />
  10:  </div>         
  11:    
  12:  <asp:Button ID="btnUpload" runat="server" 
  13:              onclick="btnUpload_Click" 
  14:              Text="Upload Files"/>
  15:  </form>

FileUpload Multiple Files In Asp.Net jQuery

Write this code in btnUpload_Click Event in code behind.

C# CODE
protected void btnUpload_Click(object sender, EventArgs e)
    {
        HttpFileCollection multipleFiles = Request.Files;
        for (int fileCount = 0; fileCount < multipleFiles.Count; fileCount++)
        {
            HttpPostedFile uploadedFile = multipleFiles[fileCount];
            string fileName = Path.GetFileName(uploadedFile.FileName);
            if (uploadedFile.ContentLength > 0 )
            {
                uploadedFile.SaveAs(Server.MapPath("~/Files/") + fileName);
                lblMessage.Text += fileName + "Saved 
"; } } }

VB.NET
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
 Dim multipleFiles As HttpFileCollection = Request.Files
 For fileCount As Integer = 0 To multipleFiles.Count - 1
  Dim uploadedFile As HttpPostedFile = multipleFiles(fileCount)
  Dim fileName As String = Path.GetFileName(uploadedFile.FileName)
  If uploadedFile.ContentLength > 0 Then
   uploadedFile.SaveAs(Server.MapPath("~/Files/") & fileName)
   lblMessage.Text += fileName & "Saved 
" End If Next End Sub


Upload Multiple Files Using JQuery
Add JQuery And it's Plugin i mentioned above in solution and add reference to these scripts in html source of page.
   1:  <head runat="server">
   2:  <title></title>
   3:  <script src="jquery.js" type="text/javascript"/>
   4:  <script src="jquery.MultiFile.js" type="text/javascript"/>
   5:  </head>

Place one FileUpload Control on page and class="multi" in it's html source.
   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <asp:FileUpload ID="FileUploadJquery" 
   4:                  runat="server" 
   5:                  class="multi"/>
   6:   
   7:  <asp:Button ID="btnJqueryMultipleFiles" 
   8:              runat="server" Text="Upload Files Using Jquery" 
   9:              onclick="btnJqueryMultipleFiles_Click"/>
  10:  </div>
  11:  </form>

Write Same code i mentioned above in Click Event of upload button, build and run the application.
JQuery Upload Multiple Files Asp.Net


Download Sample Code


1

AsyncFileUpload Example In Asp.Net For Asynchronous Uploads

This example illustrate how to use Ajax AsycFileUpload Control In Asp.Net to upload files asynchronously with use of AjaxControlToolkit OnClientUploadComplete, OnUploadedComplete and OnClientUploadError events.

Download Latest AjaxControlToolkit and put it in Bin folder of your application. register it in html source of page using Register Assembly page directive at the top of page.

Drag and place ToolkitScriptManager, AsyncFileUpload Control  and one label from toolbox on page.label will be used to display success or failure message based on OnClientUploadComplete and OnClientUploadError event raised.

We also need to reset default file size limit of 4mb to enable large file uploads.

AsyncFileUpload example in asp.net ajax

HTML SOURCE OF PAGE
Register Toolkit
   1:  <%@ Page Language="C#" AutoEventWireup="true"  
   2:           CodeFile="Default.aspx.cs" Inherits="_Default" %>
   3:  <%@ Register Assembly="AjaxControlToolkit" 
   4:               Namespace="AjaxControlToolkit" 
   5:               TagPrefix="ajax" %>
   1:  <head runat="server">
   2:      <title></title>
   3:  <script type = "text/javascript">
   4:  function Success() 
   5:  {
   6:  document.getElementById("lblMessage").innerHTML = "File Uploaded";
   7:  }
   8:   
   9:  function Error() 
  10:  {
  11:  document.getElementById("lblMessage").innerHTML = "Upload failed.";
  12:  }
  13:  </script>
  14:  </head>
  15:  <body>
  16:  <form id="form1" runat="server">
  17:  <div>
  18:  <ajax:ToolkitScriptManager ID="ToolkitScriptManager1" 
  19:                             runat="server"/>
  20:   
  21:  <ajax:AsyncFileUpload ID="AsyncFileUpload1" runat="server" 
  22:                        OnUploadedComplete="SaveUploadedFile" 
  23:                        OnClientUploadComplete="Success" 
  24:                        UploaderStyle="Modern" 
  25:                        OnClientUploadError="Error" 
  26:                        ThrobberID="loader"/>
  27:  <asp:Image ID="loader" runat="server" 
  28:             ImageUrl ="~/Loader.gif"/>
  29:   <asp:Label ID="lblMessage" runat="server" Text=""/>
  30:  </form>
  31:  </body>

C# CODE
protected void SaveUploadedFile(object sender, EventArgs e)
    {
        string uploadedFileName = Path.GetFileName(AsyncFileUpload1.FileName);
        AsyncFileUpload1.SaveAs(Server.MapPath("~/") + uploadedFileName);
    }

VB.NET
Protected Sub SaveUploadedFile(sender As Object, e As EventArgs)
 Dim uploadedFileName As String = Path.GetFileName(AsyncFileUpload1.FileName)
 AsyncFileUpload1.SaveAs(Server.MapPath("~/") & uploadedFileName)
End Sub


Download Sample Code


0

File Upload Large Files In Asp.Net Or Size Limit

If we use FileUpload Control To upload Big Or Large Files In Asp.Net,we get error message or uploading fails because of default maximum file size limit of 4mb.

we can reset this limit in web.config to enable larger file uploads.

For single application
   1:  <system.web>
   2:   
   3:  <httpRuntime executionTimeout="3600" maxRequestLength="512000"/>
   4:   
   5:  </system.web>
maxRequestLength is the maximum size allowed,this will allow files upto 500 mb to be uploaded.
executionTimeout is number of seconds upload is allowed before being shut down by ASP.NET, this also needs to be increased in case of very large file uploads.

We can allow large files to be uploaded in perticular folder or directory on server either by adding a new web.config file in folder or adding below mentioned code in main web.config.
   1:  <location path="DirectoryToUploadFiles">
   2:  <system.web>
   3:  <httpRuntime executionTimeout="3600" maxRequestLength="512000"/>
   4:  </system.web>
   5:  </location>

To apply limit settings for all the applications on server we can use web.config.comments configuration file in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG

Resetting IIS Server limits
default for IIS server is 30 mb and we can reset this in web.config as mentioned below.
   1:  <system.webServer>
   2:      <security>
   3:        <requestFiltering>
   4:          <requestLimits maxAllowedContentLength="512000"/>
   5:        </requestFiltering>
   6:      </security>
   7:  </system.webServer>

2

FileUpload In UpdatePanel HasFile Returns False Asp.Net Ajax

This example shows how to use FileUpload Control In UpdatePanel Using Asp.Net Ajax when FileUpload.HasFile method returns false inside Update Panel.

If you are uploading files with FileUpload Inside Ajax UpdatePanel, Upload fails because few controls doesn't work with Ajax Partial postbacks.

FileUpload HasFile Return False In UpdatePanel

To make full page postback for uploads to work we need to define PostBackTrigger for upload button outside ContentTemplate in html source.

HTML SOURCE
   1:  <asp:ScriptManager ID="ScriptManager1" runat="server"/>
   2:   
   3:  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
   4:  <ContentTemplate>
   5:  <asp:FileUpload ID="FileUpload1" runat="server" />
   6:  <asp:Button ID="btnUpload" runat="server" 
   7:              Text="Upload File" 
   8:              onclick="btnUpload_Click"/>
   9:  <asp:Label ID="lblMessage" runat="server"></asp:Label>
  10:  </ContentTemplate>
  11:   
  12:  <Triggers>
  13:  <asp:PostBackTrigger ControlID="btnUpload" />
  14:  </Triggers>
  15:  </asp:UpdatePanel>

Now we can write code in Click Event of Button to Upload Files With FileUpload Control In UpdatePanel.
protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fileName = FileUpload1.PostedFile.FileName;
            FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + fileName));
            lblMessage.Text = "File uploaded successfully";
        }
    }

FileUpload Control In UpdatePanel Asp.Net Ajax


1

Upload Unzip Extract Zip Files Archive In Asp.Net

This example explains how to Upload And Unzip Or Extract Zip Files Archive In Asp.Net to a Server Directory Folder then display extracted files in Gridview using C# VB.NET.

I'm using DotNetZip library for extracting zip archives, you need to putIonic.Zip.dll in BIN folder of your application.

Place one FileUpload control and Button on page to upload files, we will Upload and unzip in Click Event of Button using ExtractAll method of ZipFile object.

Place one GridView on page to Display files after extraction to a folder or directory on server.

You can Delete uploaded file from server once unzipped.

Upload and Extract Zip Files Archive on server in asp.net

HTML SOURCE OF PAGE
   1:  <asp:FileUpload ID="fileUpload1" runat="server"/>
   2:  <asp:Button ID="btnExtract" runat="server" 
   3:              onclick="btnExtract_Click" 
   4:              Text="Upload Zip Files" />
   5:      
   6:  <asp:Label ID="lblMessage" runat="server"/>
   7:   
   8:  <asp:GridView ID="gridviewExtractedFiles" runat="server" 
   9:                AutoGenerateColumns="False">
  10:  <Columns>
  11:  <asp:BoundField DataField="FileName" 
  12:                  HeaderText="File Name"/>
  13:  <asp:BoundField DataField="UncompressedSize" 
  14:                  HeaderText="Size"/>
  15:  <asp:BoundField DataField="CompressedSize"   
  16:                  HeaderText="Compressed Size">
  17:  </asp:BoundField>
  18:  </Columns>
  19:  </asp:GridView>

C# CODE
using System;
using System.IO;
using Ionic.Zip;
protected void btnExtract_Click(object sender, EventArgs e)
    {
        if (fileUpload1.HasFile)
        {
            string uploadedFile = Path.GetFileName(fileUpload1.PostedFile.FileName);
            string location = Server.MapPath("~/ZipFiles/" + uploadedFile);
            fileUpload1.SaveAs(location);
        
            ZipFile fileToExtract = ZipFile.Read(location);
            fileToExtract.ExtractAll(Server.MapPath("~/csharpdotnetfreak.blogspot.com"), ExtractExistingFileAction.DoNotOverwrite);
            gridviewExtracted.DataSource = fileToExtract.Entries;
            gridviewExtracted.DataBind();
            lblMessage.Text = "Archive extracted successfully and containes following files";
        }
   } 

We can use ExtractSelectedEntries method instead of ExtractAll to extract specific files such as *.jpg

VB.NET
Protected Sub btnExtract_Click(sender As Object, e As EventArgs)
 If fileUpload1.HasFile Then
  Dim uploadedFile As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
  Dim location As String = Server.MapPath("~/ZipFiles/" & uploadedFile)
  fileUpload1.SaveAs(location)

  Dim fileToExtract As ZipFile = ZipFile.Read(location)
  fileToExtract.ExtractAll(Server.MapPath("~/csharpdotnetfreak.blogspot.com"), ExtractExistingFileAction.DoNotOverwrite)
  gridviewExtracted.DataSource = fileToExtract.Entries
  gridviewExtracted.DataBind()
  lblMessage.Text = "Archive extracted successfully and containes following files"
 End If
End Sub
Build and run the application

Download Sample Code


20

Save Store Files In Sql Database Download From GridView Asp.Net

Upload Save Or Store Files In Ms Sql Server Database And Download In Asp.Net.

In this post i'm explaining how to save pdf,word,excel,jpeg,gif,png files in MS sqlserver database .

Save or Store files in sqlserver database asp.net

I'll also explain how to download files from sql database.

For this example i have created a sample database with table name SaveDoc to save documents in it. table schema is shown below in image.

Read Display Images In GridView From SqlServer DataBase Asp.Net to know how to save and retrieve images in sql database and display them in gridview using handler.




For uploading and saving files to database we need to use Fileupload control, so drag and place one fileupload control and one button on the aspx page in design mode.

Place one label on the page to display success or failure message, and one gridview to display uploaded documents and provide link to download document files.

I have added one button field in gridview to provide download link to file shown in respective row of gridview and this gridview is populated by sqlDataSource.

HTML SOURCE OF THE PAGE
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="btnUpload" runat="server"  
            onclick="btnUpload_Click" 
            Text="Upload"/>
</div>
<br/>
<asp:Label ID="lblMessage" runat="server">
</asp:Label><br /><br /><br />
      
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1" 
              onrowcommand="GridView1_RowCommand" 
              DataKeyNames="DocID">
<Columns>
<asp:BoundField DataField="DocID" HeaderText="DocID" 
                InsertVisible="False" 
                ReadOnly="True" 
                SortExpression="DocID" />

<asp:BoundField DataField="DocName" 
                HeaderText="DocName" 
                SortExpression="DocName" />

<asp:BoundField DataField="Type" HeaderText="Type" 
                SortExpression="Type" />
            
<asp:ButtonField ButtonType="Image"  
                ImageUrl="~/download.png" 
                CommandName="Download" 
                HeaderText="Download" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
SelectCommand="SELECT [DocID], [DocName], [Type] 
               FROM [SaveDoc]">
</asp:SqlDataSource>
</form>

To upload and save files in database write code mentioned below in Click event of upload button we placed on aspx page.

C# CODE
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Check whether FileUpload control has file 
        if (FileUpload1.HasFile)
        {
            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
            string documentType = string.Empty;

            //provide document type based on it's extension
            switch (fileExtension)
            {
                case ".pdf":
                    documentType = "application/pdf";
                    break;
                case ".xls":
                    documentType = "application/vnd.ms-excel";
                    break;
                case ".xlsx":
                    documentType = "application/vnd.ms-excel";
                    break;
                case ".doc":
                    documentType = "application/vnd.ms-word";
                    break;
                case ".docx":
                    documentType = "application/vnd.ms-word";
                    break;
                case ".gif":
                    documentType = "image/gif";
                    break;
                case ".png":
                    documentType = "image/png";
                    break;
                case ".jpg":
                    documentType = "image/jpg";
                    break;
            }

            //Calculate size of file to be uploaded
            int fileSize = FileUpload1.PostedFile.ContentLength;

            //Create array and read the file into it
            byte[] documentBinary = new byte[fileSize];
            FileUpload1.PostedFile.InputStream.Read(documentBinary, 0, fileSize);

            // Create SQL Connection 
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            // Create SQL Command and Sql Parameters 
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO SaveDoc(DocName,Type,DocData)" +
                              " VALUES (@DocName,@Type,@DocData)";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;

            SqlParameter DocName = new SqlParameter("@DocName", SqlDbType.VarChar, 50);
            DocName.Value = fileName.ToString();
            cmd.Parameters.Add(DocName);

            SqlParameter Type = new SqlParameter("@Type", SqlDbType.VarChar, 50);
            Type.Value = documentType.ToString();
            cmd.Parameters.Add(Type);

            SqlParameter uploadedDocument = new SqlParameter("@DocData", SqlDbType.Binary,fileSize);
            uploadedDocument.Value = documentBinary;
            cmd.Parameters.Add(uploadedDocument);

            con.Open();
            int result = cmd.ExecuteNonQuery();
            con.Close();
            if (result > 0)
                lblMessage.Text = "File saved to database";
            GridView1.DataBind();
        }
    }

VB.NET CODE
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
 'Check whether FileUpload control has file 
 If FileUpload1.HasFile Then
  Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
  Dim fileExtension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
  Dim documentType As String = String.Empty

  'provide document type based on it's extension
  Select Case fileExtension
   Case ".pdf"
    documentType = "application/pdf"
    Exit Select
   Case ".xls"
    documentType = "application/vnd.ms-excel"
    Exit Select
   Case ".xlsx"
    documentType = "application/vnd.ms-excel"
    Exit Select
   Case ".doc"
    documentType = "application/vnd.ms-word"
    Exit Select
   Case ".docx"
    documentType = "application/vnd.ms-word"
    Exit Select
   Case ".gif"
    documentType = "image/gif"
    Exit Select
   Case ".png"
    documentType = "image/png"
    Exit Select
   Case ".jpg"
    documentType = "image/jpg"
    Exit Select
  End Select

  'Calculate size of file to be uploaded
  Dim fileSize As Integer = FileUpload1.PostedFile.ContentLength

  'Create array and read the file into it
  Dim documentBinary As Byte() = New Byte(fileSize - 1) {}
  FileUpload1.PostedFile.InputStream.Read(documentBinary, 0, fileSize)

  ' Create SQL Connection 
  Dim con As New SqlConnection()
  con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString

  ' Create SQL Command and Sql Parameters 
  Dim cmd As New SqlCommand()
  cmd.CommandText = "INSERT INTO SaveDoc(DocName,Type,DocData)" & " VALUES (@DocName,@Type,@DocData)"
  cmd.CommandType = CommandType.Text
  cmd.Connection = con

  Dim DocName As New SqlParameter("@DocName", SqlDbType.VarChar, 50)
  DocName.Value = fileName.ToString()
  cmd.Parameters.Add(DocName)

  Dim Type As New SqlParameter("@Type", SqlDbType.VarChar, 50)
  Type.Value = documentType.ToString()
  cmd.Parameters.Add(Type)

  Dim uploadedDocument As New SqlParameter("@DocData", SqlDbType.Binary, fileSize)
  uploadedDocument.Value = documentBinary
  cmd.Parameters.Add(uploadedDocument)

  con.Open()
  Dim result As Integer = cmd.ExecuteNonQuery()
  con.Close()
  If result > 0 Then
   lblMessage.Text = "File saved to database"
  End If
  GridView1.DataBind()
 End If
End Sub


To retrieve files from database for download in click of download button we put in gridview, we need to write code mentioned below in RowCommand Event of gridview

c# CODE
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        {
            string fileName = string.Empty;
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = GridView1.Rows[index];
            int documentID = Convert.ToInt32(GridView1.DataKeys[index].Value);
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand("SELECT DocName,DocData FROM SaveDoc WHERE DocID = " + documentID, con);
            con.Open();
            SqlDataReader dReader = cmd.ExecuteReader();
            while (dReader.Read())
            {
                fileName = dReader["DocName"].ToString();
                byte[] documentBinary = (byte[])dReader["DocData"];
                FileStream fStream = new FileStream(Server.MapPath("Docs") + @"\" + fileName, FileMode.Create);
                fStream.Write(documentBinary, 0, documentBinary.Length);
                fStream.Close();
                fStream.Dispose();
            }
            con.Close();
            Response.Redirect(@"Docs\" + fileName);
        }
    }

VB.NET CODE
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
 If e.CommandName = "Download" Then
  Dim fileName As String = String.Empty
  Dim index As Integer = Convert.ToInt32(e.CommandArgument)
  Dim row As GridViewRow = GridView1.Rows(index)
  Dim documentID As Integer = Convert.ToInt32(GridView1.DataKeys(index).Value)
  Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
  Dim cmd As New SqlCommand("SELECT DocName,DocData FROM SaveDoc WHERE DocID = " & documentID, con)
  con.Open()
  Dim dReader As SqlDataReader = cmd.ExecuteReader()
  While dReader.Read()
   fileName = dReader("DocName").ToString()
   Dim documentBinary As Byte() = DirectCast(dReader("DocData"), Byte())
   Dim fStream As New FileStream(Server.MapPath("Docs") & "\" & fileName, FileMode.Create)
   fStream.Write(documentBinary, 0, documentBinary.Length)
   fStream.Close()
   fStream.Dispose()
  End While
  con.Close()
  Response.Redirect("Docs\" & fileName)
 End If
End Sub

Build and run the application.


Download Sample Code



8

Upload And Read Excel File Into DataTable DataSet Asp.Net

This example explains How To Upload And Read Excel File Data Into DataTable DataSet Using FileUpload and display in gridview using C# and VB.NET in Asp.Net.

Upload and Read Excel File Data into datatable Asp.Net
First of all put a fileUpload control, and a GridView in design view of aspx page to upload and display excel file data.

Now place a button on the page, in click even of this button we will be uploading the excel file in a folder on server and read it's content.


HTML SOURCE OF PAGE
<form id="form1" runat="server">
<div>
    
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" 
            Height="21px" Text="Upload" 
            Width="92px" onclick="btnUpload_Click"/>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>

Add these namespaces in code behind of page

using System.IO;
using System.Data.OleDb;
using System.Data;

Write below mentioned code in Click Event of Upload Button

C# CODE
protected void btnUpload_Click(object sender, EventArgs e)
    {
        string connectionString ="";
        if (FileUpload1.HasFile)
        {
            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
            string fileLocation = Server.MapPath("~/App_Data/" + fileName);
            FileUpload1.SaveAs(fileLocation);
            
            //Check whether file extension is xls or xslx

            if (fileExtension == ".xls")
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; 
            }
            else if (fileExtension == ".xlsx")
            {
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }

            //Create OleDB Connection and OleDb Command

            OleDbConnection con = new OleDbConnection(connectionString);
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Connection = con;
            OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
            DataTable dtExcelRecords = new DataTable();
            con.Open();
            DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
            cmd.CommandText = "SELECT * FROM [" + getExcelSheetName +"]";
            dAdapter.SelectCommand = cmd;
            dAdapter.Fill(dtExcelRecords);
            con.Close();
            GridView1.DataSource = dtExcelRecords;
            GridView1.DataBind();
        }
    }

VB.NET CODE

Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
 Dim connectionString As String = ""
 If FileUpload1.HasFile Then
  Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
  Dim fileExtension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
  Dim fileLocation As String = Server.MapPath("~/App_Data/" & fileName)
  FileUpload1.SaveAs(fileLocation)

  'Check whether file extension is xls or xslx

  If fileExtension = ".xls" Then
   connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
  ElseIf fileExtension = ".xlsx" Then
   connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
  End If

  'Create OleDB Connection and OleDb Command

  Dim con As New OleDbConnection(connectionString)
  Dim cmd As New OleDbCommand()
  cmd.CommandType = System.Data.CommandType.Text
  cmd.Connection = con
  Dim dAdapter As New OleDbDataAdapter(cmd)
  Dim dtExcelRecords As New DataTable()
  con.Open()
  Dim dtExcelSheetName As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
  Dim getExcelSheetName As String = dtExcelSheetName.Rows(0)("Table_Name").ToString()
  cmd.CommandText = "SELECT * FROM [" & getExcelSheetName & "]"
  dAdapter.SelectCommand = cmd
  dAdapter.Fill(dtExcelRecords)
  con.Close()
  GridView1.DataSource = dtExcelRecords
  GridView1.DataBind()
 End If
End Sub

Build and run the application.



In this code if the excel sheet contains text characters or special characters in numeric field like EmpID, then it's not read by C# or VB.NET and display blank in gridview as shown in Image.

ReadExcel Error
The reason for this is excel doesn't handle mixed data format very well, entry like 1A or 1-A etc doesn't get read by this code.

To fix this error we need to make some changes in connection string of excel, and need to add some extended properties, change the connection string as shown below.



connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + @";Extended Properties=" + Convert.ToChar(34).ToString() + @"Excel 8.0;Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();

Now it will read the excel sheet without any errors.



Download Sample Code


41

Resize Image Before/And Upload To Databse ASP.NET

Resize Image Before/And Upload To SqlServer Databse In ASP.NET 2.0,3.5,4.0 Using C# VB.NET. For this i am using FileUpload control to upload the image in datbase after resizing, and displaying Images in Gridview.

Resize Image And Upload To SqlServer Databse In ASP.NET


HTML SOURCE OF PAGE
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="btnUpload" runat="server" 
            OnClick="btnUpload_Click" Text="Upload" />
<br />
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>

<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" DataKeyNames="ID"
              DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" 
                InsertVisible="False" ReadOnly="True"
                               SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName" 
                               SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" 
           ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [ImageName], [Image] 
              FROM [Images]"></asp:SqlDataSource>
    
    </div>
    </form>


C# CODE
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;


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

    }
protected void btnUpload_Click(object sender, EventArgs e)
{
 string strImageName = txtName.Text.ToString();
 if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
 {
    string strExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
    if ((strExtension.ToUpper() == ".JPG") | (strExtension.ToUpper() == ".GIF"))
    {
     // Resize Image Before Uploading to DataBase
      System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
      int imageHeight = imageToBeResized.Height;
      int imageWidth = imageToBeResized.Width;
      int maxHeight = 240;
      int maxWidth = 320;
      imageHeight = (imageHeight * maxWidth) / imageWidth;
      imageWidth = maxWidth;

              if (imageHeight > maxHeight)
                {
                    imageWidth = (imageWidth * maxHeight) / imageHeight;
                    imageHeight = maxHeight;
                }

                Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
                System.IO.MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                stream.Position = 0;
                byte[] image = new byte[stream.Length + 1];
                stream.Read(image, 0, image.Length);



                // Create SQL Connection 
                SqlConnection con = new SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

                // Create SQL Command 

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;

                SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
                ImageName.Value = strImageName.ToString();
                cmd.Parameters.Add(ImageName);

                SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, image.Length);
                UploadedImage.Value = image;
                cmd.Parameters.Add(UploadedImage);
                con.Open();
                int result = cmd.ExecuteNonQuery();
                con.Close();
                if (result > 0)
                    lblMessage.Text = "File Uploaded";
                GridView1.DataBind();
            }
        }
    }
}


VB.NET
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Data.SqlClient
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D
Imports System.Drawing


Public Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        
    End Sub
    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim strImageName As String = txtName.Text.ToString()
        If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
            Dim strExtension As String = System.IO.Path.GetExtension(FileUpload1.FileName)
            If (strExtension.ToUpper() = ".JPG") Or (strExtension.ToUpper() = ".GIF") Then
                ' Resize Image Before Uploading to DataBase
                Dim imageToBeResized As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
                Dim imageHeight As Integer = imageToBeResized.Height
                Dim imageWidth As Integer = imageToBeResized.Width
                Dim maxHeight As Integer = 240
                Dim maxWidth As Integer = 320
                imageHeight = (imageHeight * maxWidth) / imageWidth
                imageWidth = maxWidth
                
                If imageHeight > maxHeight Then
                    imageWidth = (imageWidth * maxHeight) / imageHeight
                    imageHeight = maxHeight
                End If
                
                Dim bitmap As New Bitmap(imageToBeResized, imageWidth, imageHeight)
                Dim stream As System.IO.MemoryStream = New MemoryStream()
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
                stream.Position = 0
                Dim image As Byte() = New Byte(stream.Length) {}
                stream.Read(image, 0, image.Length)
                
                
                
                ' Create SQL Connection 
                Dim con As New SqlConnection()
                con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
                
                ' Create SQL Command 
                
                Dim cmd As New SqlCommand()
                cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)"
                cmd.CommandType = CommandType.Text
                cmd.Connection = con
                
                Dim ImageName As New SqlParameter("@ImageName", SqlDbType.VarChar, 50)
                ImageName.Value = strImageName.ToString()
                cmd.Parameters.Add(ImageName)
                
                Dim UploadedImage As New SqlParameter("@Image", SqlDbType.Image, image.Length)
                UploadedImage.Value = image
                cmd.Parameters.Add(UploadedImage)
                con.Open()
                Dim result As Integer = cmd.ExecuteNonQuery()
                con.Close()
                If result > 0 Then
                    lblMessage.Text = "File Uploaded"
                End If
                GridView1.DataBind()
            End If
        End If
    End Sub
End Class
Hope this helps

Download sample code attached



Find More Articles