'Upload and save image to server without refresh using Ajax and ASP.NET

I have a VB ASP.net page that allow user to upload, crop and save the image and this hapens in a dialog so I don't want to refresh the page. So, I'm trying to use Ajax and not sure if it's possible.

Is there a way to let this work using my code? and if not is there a simple solution?

Note: I tested all these ASP codes and worked fine without Ajax

The regular upload is like:

Private Sub btnUpoadToCrop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpoadToCrop.Click

    Dim objUpload As New Upload
    objUpload.MaxLength = 4000000

    '''' Upload Image File
    If objUpload.FileFieldLength(flImg) <> 0 Then

        Dim flImg As HttpPostedFile = Request.Files(0)
        Dim oFolder As String = "\media\temp-uploads\"
        Dim strName As String = System.IO.Path.GetFileName(flImg.FileName).Replace(" " & "%20", "_").ToString
        Dim oFile As String = oFolder + strName

        '''' Save Original Photo
        flImg.SaveAs(HttpContext.Current.Server.MapPath(oFile))


    End If

End Sub

TRY AJAX

And because I couldn't access the flImg Image filed so tried to send variables from Ajax which didn't work with me and the console returning 500 (Internal Server Error)

VB.NET

   Public Shared Function UploadSource(ByVal src As String, ByVal strName As String, ByVal ext As String) As String

    '''' Upload Image File

    Dim filesCollection As HttpFileCollection = HttpContext.Current.Request.Files
    Dim fileName = filesCollection(0)
    Dim Name As String = System.IO.Path.GetFileName(fileName.FileName).Replace(" " & "%20", "_").ToString

    Dim oFolder As String = "\media\temp-uploads\"
    Dim oFile As String = oFolder + Name

    '''' Save Original Photo

    fileName.SaveAs(HttpContext.Current.Server.MapPath(oFile))

End Function

jQUERY

    $(document).ready(function() {

        // Ajax Upload
        var _src, _path, _name, _ext;
        $("#<%= flImg.ClientID%>").change(function () {
            //console.dir(this.files[0]);
            var val = $(this).val();    
            if (val != "") {
                _src = val;
                _name = _src.substr(0, _src.lastIndexOf('.'));
                _ext = _src.split('.').pop();
                _ext = _ext.toLowerCase();
                alert(_ext);
            }
            else {
                _src = "";
            }
        }).trigger('change');
        $(document).on("click", "#UploadSource", function () {
            if (_src != "") {
                alert(_name);
                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    url: '/ImgCropper.aspx/UploadSource',
                    // *** I have set values for variables for test
                    data: "{'src':'" + "xyz.jpg" + "','name':'" + "xyz"+ "','ext':'" + "jpg" + "'}",
                    async: false,
                    success: function (response) {

                   },
                   error: function () {
                       alert("some problem in saving data");
                   }
               });
            }


        });
     });

Then tried without sending variables in Ajax data with this function and with no hope still:

Public Shared Function UploadSource() As String


    '''' Upload Image File

    Dim filesCollection As HttpFileCollection = HttpContext.Current.Request.Files
    Dim fileName = filesCollection(0)
    Dim Name As String = System.IO.Path.GetFileName(fileName.FileName).Replace(" " & "%20", "_").ToString


    Dim oFolder As String = "\media\temp-uploads\"
    Dim oFile As String = oFolder + Name

    '''' Save Original Photo
    fileName.SaveAs(HttpContext.Current.Server.MapPath(oFile))


End Function


Solution 1:[1]

Please download ajax file uplod script by using below link.

http://www.phpletter.com/DOWNLOAD/

Then your code should be like below.

Html:

<input type="file" id="fileupload" name="upload"/>

<asp:LinkButton ID="btnSave" runat="server" Text="Save" Width="52px"  OnClientClick="UploadFile();" />

Jquery:

$(document).ready(function () {
function UploadFile() {
var fileName = $('#fileupload').val().replace(/.*(\/|\\)/, '');

if (fileName != "") {
                $.ajaxFileUpload({ url: 'AjaxFileUploader.ashx',
                    secureuri: false,
                    fileElementId: 'fileupload',
                    dataType: 'json',
                    success: function (data, status) {
                        if (typeof (data.error) != 'undefined') {
                            if (data.error != '') {
                                alert(data.error);
                            } else {
                                alert('Success')
                            }
                        }
                    },
                    error: function (data, status, e) {
                        alert(e);
                    }
                }
                )
            }
}

});

AjaxFileUploader.ashx:

<%@ WebHandler Language="VB" Class="AjaxFileUploader" %>
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Text
Public Class AjaxFileUploader
    Implements IHttpHandler
    Implements System.Web.SessionState.IRequiresSessionState

    Public Sub ProcessRequest(context As HttpContext)


        If context.Request.Files.Count > 0 Then
            Dim path__1 As String = context.Server.MapPath("~/Uploads")
            If Not Directory.Exists(path__1) Then
                Directory.CreateDirectory(path__1)
            End If

            Dim file = context.Request.Files(0)

            Dim fileName As String

            If HttpContext.Current.Request.Browser.Browser.ToUpper() = "IE" Then
                Dim files As String() = file.FileName.Split(New Char() {"\"C})
                fileName = files(files.Length - 1)
            Else
                fileName = file.FileName
            End If
            Dim newFile As String = Guid.NewGuid().ToString()
            Dim fInfo As New FileInfo(fileName)
            newFile = String.Format("{0}{1}", newFile, fInfo.Extension)
            Dim strFileName As String = newFilename
            fileName = Path.Combine(path__1, newFile)
            file.SaveAs(fileName)


            Dim msg As String = "{"
            msg += String.Format("error:'{0}'," & vbLf, String.Empty)
            msg += String.Format("msg:'{0}'" & vbLf, strFileName)
            msg += "}"


            context.Response.Write(msg)
        End If
    End Sub

    Public ReadOnly Property IsReusable() As Boolean
        Get
            Return True
        End Get
    End Property
End Class

Solution 2:[2]

You can write WebMethod as following(its in C#)

[WebMethod]
public string UploadFile()
        {
                var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
                //Your logic to save httpPostedFile
            }
        }

And on the page you can send file using jQuery as following,

<html>
<div>
        Select File to Upload:
        <input id="fileUpload" type="file" />
        <input id="btnUploadFile" type="button" value="Upload File" /></div>
 <script type="text/javascript">

    $('#btnUploadFile').on('click', function () {
    $('#<%=hdnFileName.ClientID %>').val('');
        if (typeof FormData == "undefined") {
            alert("Please Use Latest Version Of Google Chrome Or Mozilla Firefox To Upload Documents");
            return false;
        }
                    var data = new FormData();

                    var files = $("#fileUpload").get(0).files;

                    // Add the uploaded image content to the form data collection
                    if (files.length > 0) {
                        data.append("UploadedImage", files[0]);
                    }
    else{
    alert('Please Select File');
    return;
    }

                    var ajaxRequest = $.ajax({
                        type: "POST",
                        url: "http://localhost/WebSite/WebPage.aspx/UploadFiles",
                        contentType: false,
                        processData: false,
                        data: data
                    });

                    ajaxRequest.done(function (data) {
                        console.log(data);
                        alert("done");
                    });

                    ajaxRequest.error(function (xhr, status) {
                        console.log(xhr);
                        console.log(status);
                        alert(status);
                    });
                });
</script>
</html>

Remember, it may not work on some versions of IE, otherwise it works in Chrome and Firefox smoothly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 AbdulRahman Ansari