Rename and Resize image when saving in ASP.Net using jQuery Ajax and Generic Handler

Jilsoft
 
on Mar 16, 2022 10:44 AM
Sample_384354.zip
467 Views

How do i rename the image when saving

How do i also resize the image when saving

[Solved] ASP.Net jQuery Ajax Error: Could not find file C:\\fakepath

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm3.aspx.vb" Inherits="Love.WebForm3" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <script src="assets/js/core/jquery.3.2.1.min.js" type="text/javascript"></script>       
     <script type="text/javascript">
         $(function () {
             $('#btnSave').on("click", function () {
                 document.getElementById("fuUpload").height = "100"
                 document.getElementById("fuUpload").width = "100"
                 var formData = new FormData();
                 for (var i = 0; i < $("#fuUpload").prop("files").length; i++) {
                     formData.append($("#fuUpload").prop("files")[i].name, $("#fuUpload").prop("files")[i]);
                 }
                 formData.append("Name", $("#txtName").val());
                 $.ajax({
                     type: 'POST',
                     url: "Handler.ashx",
                     data: formData,
                     cache: false,
                     contentType: false,
                     processData: false,
                     success: function (r) {
                         alert(r.d);
                     },
                     error: function (r) {
                      
                     }
                 })
                 return false;
             });
         });
</script>  
</head>
<body>
    <form id="form1" runat="server">
     <div>
    <input type="file" name="fuUpload" id="fuUpload" multiple="multiple" />
    <input name="txtName" type="text" id="txtName" />
    <asp:Button ID="btnSave" runat="server" Text="Save" value="Save" />
</div>
    </form>
</body>
</html>

 

Imports System
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.IO
 
Public Class Handler : Implements IHttpHandler
 
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        If context.Request.Files.Count > 0 Then
            Dim name As String = context.Request("Name")
            For Each fName As String In context.Request.Files
                Dim file As HttpPostedFile = context.Request.Files(fName)
                file.SaveAs(HttpContext.Current.Server.MapPath("~/Files/" & Path.GetFileName(file.FileName)))
                SaveDetails(name, "~/Files/" & Path.GetFileName(file.FileName), Path.GetFileName(file.FileName))
            Next
        End If
    End Sub
 
    Private Shared Sub SaveDetails(ByVal name As String, ByVal filePath As String, ByVal fileName As String)
        Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
        Using con As SqlConnection = New SqlConnection(strConnString)
            con.Open()
            Using cmd As SqlCommand = New SqlCommand("Insert INTO Files (Name,FilePath,FileName) values (@Name,@FilePath,@FileName)", con)
                cmd.Parameters.AddWithValue("@Name", name)
                cmd.Parameters.AddWithValue("@FilePath", filePath)
                cmd.Parameters.AddWithValue("@FileName", fileName)
                cmd.ExecuteNonQuery()
            End Using
            con.Close()
        End Using
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
 
End Class

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 17, 2022 12:16 PM

Hi Jilsoft,

Refer below example.

HTML

<div>
    <input type="file" name="fuUpload" id="fuUpload" multiple="multiple" />
    <input name="txtName" type="text" id="txtName" />
    <asp:Button ID="btnSave" runat="server" Text="Save" value="Save" />
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('#btnSave').on("click", function () {
            var formData = new FormData();
            for (var i = 0; i < $("#fuUpload").prop("files").length; i++) {
                formData.append($("#fuUpload").prop("files")[i].name, $("#fuUpload").prop("files")[i]);
            }
            formData.append("Name", $('#txtName').val());
            $.ajax({
                type: 'POST',
                url: "Handler.ashx",
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (r) {
                    
                },
                error: function (r) {
                    alert(r.responseText);
                }
            })
            return false;
        });
    });
</script>

Handler

C#

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

using System;
using System.Web;
using System.Configuration;
using System.Drawing.Imaging;
using System.Data.SqlClient;
using System.IO;

public class Handler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.Files.Count > 0)
        {
            string name = context.Request["Name"];
            foreach (string fName in context.Request.Files)
            {
                HttpPostedFile postedFile = context.Request.Files[fName];
                byte[] bytes;
                string filePath = postedFile.FileName;
                System.Drawing.Image image = System.Drawing.Image.FromStream(postedFile.InputStream);
                // Resize image.
                using (System.Drawing.Image thumbnail = image.GetThumbnailImage(100, 100, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        thumbnail.Save(memoryStream, ImageFormat.Png);
                        bytes = new Byte[memoryStream.Length];
                        memoryStream.Position = 0;
                        memoryStream.Read(bytes, 0, (int)bytes.Length);
                    }
                }
                string newFilePath = "~/Files/" + Path.GetFileNameWithoutExtension(postedFile.FileName) + DateTime.Now.ToString("Hhmmss") + Path.GetExtension(postedFile.FileName);
                File.WriteAllBytes(HttpContext.Current.Server.MapPath(newFilePath), bytes);
                SaveDetails(name, newFilePath, Path.GetFileName(HttpContext.Current.Server.MapPath(newFilePath)));
            }
        }
    }

    private static void SaveDetails(string name, string filePath, string fileName)
    {
        string str = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        using (SqlConnection con = new SqlConnection(str))
        {
            con.Open();
            using (SqlCommand cmd = new SqlCommand("Insert INTO Files (Name,FilePath,FileName) values (@Name,@FilePath,@FileName)", con))
            {
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@FilePath", filePath);
                cmd.Parameters.AddWithValue("@FileName", fileName);
                cmd.ExecuteNonQuery();
            }
            con.Close();
        }
    }

    public bool ThumbnailCallback()
    {
        return false;
    }

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

VB.Net

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

Imports System
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Drawing.Imaging
Imports System.IO

Public Class Handler : Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        If context.Request.Files.Count > 0 Then
            Dim name As String = context.Request("Name")
            For Each fName As String In context.Request.Files
                Dim postedFile As HttpPostedFile = context.Request.Files(fName)
                Dim bytes As Byte()
                Dim filePath As String = postedFile.FileName
                Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(postedFile.InputStream)
                ' Resize image.
                Using thumbnail As System.Drawing.Image = image.GetThumbnailImage(100, 100, New System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback), IntPtr.Zero)
                    Using memoryStream As MemoryStream = New MemoryStream()
                        thumbnail.Save(memoryStream, ImageFormat.Png)
                        bytes = New Byte(memoryStream.Length - 1) {}
                        memoryStream.Position = 0
                        memoryStream.Read(bytes, 0, CInt(bytes.Length))
                    End Using
                End Using

                Dim newFilePath As String = "~/Files/" & Path.GetFileNameWithoutExtension(postedFile.FileName) + DateTime.Now.ToString("Hhmmss") + Path.GetExtension(postedFile.FileName)
                File.WriteAllBytes(HttpContext.Current.Server.MapPath(newFilePath), bytes)
                SaveDetails(name, newFilePath, Path.GetFileName(HttpContext.Current.Server.MapPath(newFilePath)))
            Next
        End If
    End Sub

    Private Shared Sub SaveDetails(ByVal name As String, ByVal filePath As String, ByVal fileName As String)
        Dim str As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
        Using con As SqlConnection = New SqlConnection(str)
            con.Open()
            Using cmd As SqlCommand = New SqlCommand("Insert INTO Files (Name,FilePath,FileName) values (@Name,@FilePath,@FileName)", con)
                cmd.Parameters.AddWithValue("@Name", name)
                cmd.Parameters.AddWithValue("@FilePath", filePath)
                cmd.Parameters.AddWithValue("@FileName", fileName)
                cmd.ExecuteNonQuery()
            End Using
            con.Close()
        End Using
    End Sub

    Public Function ThumbnailCallback() As Boolean
        Return False
    End Function

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