Upload multiple file using Multiple FileUpload control and Handler in ASP.Net

Last Reply one month ago By pandeyism

Posted one month ago

how can use two fileupload in same page

i used for single it work  but as well as i add second fileupload control it stop working 

function updateFile() {
    $.ajax({
        url: 'HandlerCS.ashx',
        type: 'POST',
        data: new FormData($('form')[0]),
        cache: false,
        contentType: false,
        processData: false,
        success: function (file) {
            $("#blah").attr('src', "../images/images.jpg");
            $('#imgInp').val('');
            swal({
                title: 'Warning',
                text: file.name,
                type: 'warning',
                confirmButtonText: 'OK',
                confirmButtonColor: "#134d8a"
            });
        }
    });
}

 

<%@ WebHandler Language="C#" Class="HandlerCS" %>
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;
using System.Drawing;
using System.Drawing.Drawing2D;

public class HandlerCS : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //Check if Request is to Upload the File.
        if (context.Request.Files.Count > 0)
        {
            //Fetch the Uploaded File.
            HttpPostedFile postedFile = context.Request.Files[0];

            //Set the File Name.
            string fileName = Path.GetFileName(postedFile.FileName);
            string extension = Path.GetExtension(fileName);
            if (extension.ToLower() != ".jpg" && extension.ToLower() != ".jpeg" && extension.ToLower() != ".png")
            {
                string json2 = new JavaScriptSerializer().Serialize(
                new
                {
                    name = "Only Jpg and jpeg and png Format Accepted..."
                });

                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.ContentType = "text/json";
                context.Response.Write(json2);
                context.Response.End();
                return;
            }

            if (File.Exists(context.Server.MapPath("~/AdminPannel/UploadingImg/") + fileName))
            {
                File.Delete(context.Server.MapPath("~/AdminPannel/UploadingImg/" + fileName));
            }

            Stream strm = postedFile.InputStream;
            using (var image = System.Drawing.Image.FromStream(strm))
            {
                // Print Original Size of file (Height or Width) 
                int newWidth = 350; // New Width of Image in Pixel 
                int newHeight = 350; // New Height of Image in Pixel 
                var thumbImg = new Bitmap(newWidth, newHeight);
                var thumbGraph = Graphics.FromImage(thumbImg);
                thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
                thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
                thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                var imgRectangle = new Rectangle(0, 0, newWidth, newHeight);
                thumbGraph.DrawImage(image, imgRectangle);
                // Save the file 
                string targetPath = context.Server.MapPath(@"~/AdminPannel/UploadingImg/") + fileName;
                thumbImg.Save(targetPath, image.RawFormat);
            }

            //Send File details in a JSON Response.
            string json = new JavaScriptSerializer().Serialize(
            new
            {
                name = fileName + " " + "Has been Uploaded SucessFully..."
            });

            context.Response.StatusCode = (int)HttpStatusCode.OK;
            context.Response.ContentType = "text/json";
            context.Response.Write(json);
            context.Response.End();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

 

You are viewing reply posted by: pandeyism one month ago.
Posted one month ago

Hi SajidHussa,

Refer below sample.

HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    function updateFile() {
        var formData = new FormData();
        for (var i = 0; i < $(".File").length; i++) {
            formData.append($(".File")[i].files[0].name, $(".File")[i].files[0]);
        }
        $.ajax({
            url: 'Handler.ashx',
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                alert(result.name + " Has been Uploaded SucessFully...");
            }, error: function (r) {
                alert(r.d);
            }
        });
    }
</script>
<div>
    <input type="file" id="fuUpload1" class="File" />
    <br />
    <input type="file" id="fuUpload2" class="File" />
    <br />
    <input type="button" value="Upload" onclick="updateFile()" />
    <br />
</div>

Handler

C#

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.IO;
using System.Collections.Generic;

public class Handler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        List<string> names = new List<string>();
        for (int i = 0; i < context.Request.Files.Count; i++)
        {
            HttpPostedFile postedFile = context.Request.Files[i];
            string fileName = Path.GetFileName(postedFile.FileName);
            if (File.Exists(context.Server.MapPath("~/images/") + fileName))
            {
                File.Delete(context.Server.MapPath("~/images/" + fileName));
            }
            Stream strm = postedFile.InputStream;
            using (var image = System.Drawing.Image.FromStream(strm))
            {
                int newWidth = 350;
                int newHeight = 350;
                var thumbImg = new System.Drawing.Bitmap(newWidth, newHeight);
                var thumbGraph = System.Drawing.Graphics.FromImage(thumbImg);
                thumbGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                thumbGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                thumbGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                var imgRectangle = new System.Drawing.Rectangle(0, 0, newWidth, newHeight);
                thumbGraph.DrawImage(image, imgRectangle);
                string targetPath = context.Server.MapPath(@"~/images/") + fileName;
                thumbImg.Save(targetPath, image.RawFormat);
            }
            names.Add(fileName);
        }
        //Send File details in a JSON Response.
        string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new { name = names });
        context.Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
        context.Response.ContentType = "text/json";
        context.Response.Write(json);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

VB.Net

<%@ WebHandler Language="VB" Class="Handler" %>

Imports System
Imports System.Web
Imports System.IO

Public Class Handler : Implements IHttpHandler
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim names As List(Of String) = New List(Of String)()
        For i As Integer = 0 To context.Request.Files.Count - 1
            Dim postedFile As HttpPostedFile = context.Request.Files(i)
            Dim fileName As String = Path.GetFileName(postedFile.FileName)
            If File.Exists(context.Server.MapPath("~/images/") & fileName) Then
                File.Delete(context.Server.MapPath("~/images/" & fileName))
            End If

            Dim strm As Stream = postedFile.InputStream
            Using image = System.Drawing.Image.FromStream(strm)
                Dim newWidth As Integer = 350
                Dim newHeight As Integer = 350
                Dim thumbImg = New System.Drawing.Bitmap(newWidth, newHeight)
                Dim thumbGraph = System.Drawing.Graphics.FromImage(thumbImg)
                thumbGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
                thumbGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
                thumbGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
                Dim imgRectangle = New System.Drawing.Rectangle(0, 0, newWidth, newHeight)
                thumbGraph.DrawImage(image, imgRectangle)
                Dim targetPath As String = context.Server.MapPath("~/images/") & fileName
                thumbImg.Save(targetPath, image.RawFormat)
            End Using
            names.Add(fileName)
        Next

        Dim json As String = New System.Web.Script.Serialization.JavaScriptSerializer().Serialize(New With {Key .name = names})
        context.Response.StatusCode = CInt(System.Net.HttpStatusCode.OK)
        context.Response.ContentType = "text/json"
        context.Response.Write(json)
    End Sub
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Screenshot