In this article I will explain with an example, how to upload File with Web Service (ASMX) using jQuery AJAX in ASP.Net using C# and VB.Net.
The Web Service (ASMX) will be used to upload and save files in Folder (Directory) in ASP.Net.
The Web Service (ASMX) will be called using jQuery AJAX and the file will be uploaded to Folder (Directory) with Progress Bar using HTML5 Form Data and XmlHttpRequest (XHR).
 
 
Web Service
Following is the Web Service (ASMX) for uploading the Files, first the Folder (Directory) where the Files will be saved is created if it does not exist.
Then the Name of the File is read from Request.Form collection and the File is read from the Request.Files collection and saved in the Folder (Directory) created earlier.
Finally, an OK response along with the Name of the File is returned to the Client which confirms successful upload of the File.
C#
using System;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Net;
 
///<summary>
/// Summary description for UploadService.
///</summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class UploadService : System.Web.Services.WebService {
 
    public UploadService()
    {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }
 
    [WebMethod]
    public void UploadFiles()
    {
        //Create the Directory.
        string path = HttpContext.Current.Server.MapPath("~/Uploads/");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        //Fetch the File.
        HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];
 
        //Fetch the File Name.
        string fileName = HttpContext.Current.Request.Form["fileName"] + Path.GetExtension(postedFile.FileName);
 
        //Save the File.
        postedFile.SaveAs(path + fileName);
 
        //Send OK Response to Client.
        HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.OK;
        HttpContext.Current.Response.Write(fileName);
        HttpContext.Current.Response.Flush();
    }
}
 
VB.Net
Imports System.Web
Imports System.Web.Services
Imports System.IO
Imports System.Net
 
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class UploadService
    Inherits System.Web.Services.WebService
 
    <WebMethod()> _
    Public Sub UploadFiles()
        'Create the Directory.
        Dim folderPath As String = HttpContext.Current.Server.MapPath("~/Uploads/")
        If Not Directory.Exists(folderPath) Then
            Directory.CreateDirectory(folderPath)
        End If
 
        'Fetch the File.
        Dim postedFile As HttpPostedFile = HttpContext.Current.Request.Files(0)
 
        'Fetch the File Name.
        Dim fileName As String = HttpContext.Current.Request.Form("fileName") + Path.GetExtension(postedFile.FileName)
 
        'Save the File.
        postedFile.SaveAs(folderPath & fileName)
 
        'Send OK Response to Client.
        HttpContext.Current.Response.StatusCode = CInt(HttpStatusCode.OK)
        HttpContext.Current.Response.Write(fileName)
        HttpContext.Current.Response.Flush()
    End Sub
End Class
 
 
Adding Web Reference of Web Service
Next thing you need to do is add the Web Reference of the Web Service so that it can be used on the ASP.Net Web page.
Please refer the following article for instructions in adding Web Reference of Web Service: How to add reference of Web Service (ASMX) in ASP.Net using Visual Studio.
 
 
HTML Markup
The HTML Markup consists an HTML FileUpload element and a Button. Below the Form there’s an HTML5 Progress element for displaying the progress of the uploading File.
The Upload Button has been assigned a jQuery Click event handler. When the Upload Button is clicked, the File is read from the HTML FileUpload element and added to an HTML5 FormData JavaScript object and then the File is uploaded using the Web Service (ASMX) using XmlHttpRequest (XHR).
A Progress event handler is attached to the XmlHttpRequest (XHR), which displays the progress of the File being uploaded using the HTML5 Progress element.
The Name of the File is fetched from the TextBox and is added to the FormData object along with the File.
Finally, the received Name of the uploaded File is displayed in an HTML SPAN element.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>Name:</td>
            <td><input type="text" id="fileName" /></td>
        </tr>
        <tr>
            <td>File:</td>
            <td><input type="file" id="file" /></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" id="btnUpload" value="Upload" /></td>
        </tr>
        <tr>
            <td colspan="2"><progress id="fileProgress" style="display: none"></progress></td>
        </tr>
    </table>
    <hr/>
    <span id="lblMessage" style="color: Green"></span>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("body").on("click", "#btnUpload", function () {
            var formData = new FormData();
            formData.append("fileName", $("#fileName").val());
            formData.append("file", $("#file")[0].files[0]);
            $.ajax({
                url: 'UploadService.asmx/UploadFiles',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (fileName) {
                    $("#fileProgress").hide();
                    $("#lblMessage").html("<b>" + fileName + "</b> has been uploaded.");
                },
                xhr: function () {
                    var fileXhr = $.ajaxSettings.xhr();
                    if (fileXhr.upload) {
                        $("progress").show();
                        fileXhr.upload.addEventListener("progress", function (e) {
                            if (e.lengthComputable) {
                                $("#fileProgress").attr({
                                    value: e.loaded,
                                    max: e.total
                                });
                            }
                        }, false);
                    }
                    return fileXhr;
                }
            });
        });
    </script>
    </form>
</body>
</html>
 
 
Screenshot
Upload File with Web Service (ASMX) using jQuery AJAX in ASP.Net
 
 
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads