Sunday 2 September 2018

Multiple image upload and Restrict file size


Multiple image upload and Restrict file size using Asp.Net C#

HTML Coding

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageUpload.aspx.cs" Inherits="ImageUpload" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Multiple image upload and Restrict file size using Asp.Net C#</title>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center">
        <br />
        <asp:FileUpload ID="FileUpload1" AllowMultiple="True" runat="server" />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

C# Coding

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbcon"].ToString());
        con.Open();
        HttpFileCollection hfcc = Request.Files;

        if (hfcc.Count != 0)   // 
        {
            // Allow Only 2 Images
            if (hfcc.Count <= 2)
            {
                if (FileUpload1.PostedFile.ContentLength < 1048576)            // Allow Size upto 1MB
                {
                    HttpFileCollection hfc = Request.Files;
                    for (int i = 0; i < hfc.Count; i++)
                    {
                        HttpPostedFile hpf = hfc[i];
                        if (hpf.ContentLength > 0)
                        {
                            hpf.SaveAs(Server.MapPath("Image") + "\\" + Path.GetFileName(hpf.FileName));                           
                            SqlCommand cmd = new SqlCommand("insert into Reg(imagename,imgpath) values ('" +hpf.FileName+ "','" +"Image/"+hpf.FileName  + "')", con);
                            cmd.ExecuteNonQuery();
                        }
                        
                    }
                    con.Close();
                    Response.Write("<script>alert('Image Uploaded')</script>");                    
                }
                else
                {
                    Response.Write("<script>alert('Maximum File Size 1MB')</script>");
                }
            }
            else
            {
                Response.Write("<script>alert('Allowed only 2 Images')</script>");
            }
        }
        else
        {
            Response.Write("<script>alert('Atleast One Image Upload')</script>");
        }

    }
}

No comments:

Post a Comment