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

Jilsoft
 
on Mar 13, 2022 11:02 PM
Sample_232719.zip
1252 Views

i get this error 

{"Message":"Could not find file \u0027C:\\fakepath\\001.jpeg\u0027.","StackTrace":" at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)\r\n at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)\r\n at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)\r\n at System.IO.FileStream..ctor(String path, FileMode mode)\r\n at Love.WebForm2.Save(List`1 files, String name) in C:\\Users\\SERVER\

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#btnSave').on("click", function () {
                var files = new Array();
                for (var i = 0; i < $("#fuUpload").prop("files").length; i++) {
                    var file = {};
                    file.Name = $("#fuUpload").prop("files")[i].name;
                    file.Path = $("#fuUpload").val().split(', ')[i];
                    files.push(file);
                }
                var name = $('#txtName').val();
                $.ajax({
                    type: 'POST',
                    url: "CS.aspx/Save",
                    data: '{files:' + JSON.stringify(files) + ',name:"' + name + '"}',
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (r) {
                        alert(r.d);
                    },
                    error: function (r) {
                        alert(r.responseText);
                    }
                })
                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" />
        <input type="submit" name="btnSave" value="Save" id="btnSave" />
    </div>
    </form>
</body>
</html>

 

<System.Web.Services.WebMethod> _
Public Shared Sub Save(files As List(Of FileDetails), name As String)
    For i As Integer = 0 To files.Count - 1
        Dim stream As New FileStream(files(i).Path, FileMode.Open)
        Dim fileStream = New FileStream(HttpContext.Current.Server.MapPath("~/Files/" + files(i).Name), FileMode.Create, FileAccess.Write)
        stream.CopyTo(fileStream)
        fileStream.Dispose()
        SaveDetails(name, HttpContext.Current.Server.MapPath("~/Files/" + files(i).Name), files(i).Name)
    Next
End Sub
 
Private Shared Sub SaveDetails(name As String, filePath As String, fileName As String)
    Dim str As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
    Using con As New SqlConnection(str)
        con.Open()
        Using cmd As 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 Class FileDetails
    Public Property Name() As String
        Get
            Return m_Name
        End Get
        Set
            m_Name = Value
        End Set
    End Property
    Private m_Name As String
    Public Property Path() As String
        Get
            Return m_Path
        End Get
        Set
            m_Path = Value
        End Set
    End Property
    Private m_Path As String
End Class

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 14, 2022 05:00 AM
on Mar 15, 2022 11:31 AM

Hi Jilsoft,

Use Generic Handler to upload the files using FormData and jQuery Ajax.

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) {
                    alert(r.d);
                },
                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.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 file = 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));
            }
        }
    }

    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 IsReusable
    {
        get
        {
            return false;
        }
    }
}

VB.Net

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

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 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 ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class