In this article I will explain with an example, how to save (upload) Image files to Server using Spider web API in ASP.Cyberspace MVC Razor.

The Image files will exist uploaded to Web API and and then within the Web API, the Prototype files will be saved in Folder (Directory) on the Server's Disk in ASP.Net MVC Razor.

Namespaces

You will need to import the following namespaces.

using Arrangement.IO;

using System.Net;

using System.Cyberspace.Http;

using Organization.Web;

using Organisation.Web.Http;

Controller

The Controller consists of the following Activeness method.

Activeness method for handling Get functioning

Inside this Action method, simply the View is returned.

public form HomeController : Controller

{

// Become: Home

public ActionResult Alphabetize()

    {

return View();

    }

}

Web API Controller

In order to add a Web API Controller, yous will need to Right Click the Controllers binder in the Solution Explorer and click on Add together and and so Controller.

Now from the Add together Scaffold window, cull the Web API ii Controller – Empty selection as shown below.

Web API: Save (Upload) image to Server in ASP.Net MVC

And then give it a suitable name and click Add.

Web API: Save (Upload) image to Server in ASP.Net MVC

The next task is to register the Configuration for Web API in the Global.asax file and so that the Spider web API is available for accessing on Web.

In club to practise so open Global.asax file and add the following line.

Organisation.Web.Http. GlobalConfiguration .Configure( WebApiConfig .Register);

Make certain you add it in the same club as shown below.

public class MvcApplication : System.Web. HttpApplication

{

protected void Application_Start()

    {

AreaRegistration .RegisterAllAreas();

        System.Web.Http. GlobalConfiguration .Configure( WebApiConfig .Annals);

RouteConfig .RegisterRoutes( RouteTable .Routes);

    }

}

The adjacent step is to code the Web API Controller. The Web API Controller consists of the following two Action methods.

Action method for uploading the Epitome Files

Inside this Action method, first the Folder (Directory) where the Files will be saved is created if it does not exists.

Then the Name of the Image File is read from Request.Grade collection and the Image File is read from the Request.Files collection and saved in the Binder (Directory) created earlier.

Finally, an OK response forth with the name of the Epitome File is returned to the Client which confirms successful upload of the Paradigm File.

Action method for getting Listing of Files

Inside this Action method, the records of Paradigm Files are fetched from the Folder (Directory) and the List is returned to Client using HttpResponseMessage object.

public class ImageAPIController : ApiController

{

    [ Route ( "api/ImageAPI/UploadFiles" )]

    [ HttpPost ]

public HttpResponseMessage UploadFiles()

    {

//Create the Directory.

cord 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 Proper noun.

cord fileName = Path .GetFileName(postedFile.FileName);

//Salve the File.

        postedFile.SaveAs(path + fileName);

//Transport OK Response to Client.

render Request.CreateResponse( HttpStatusCode .OK, fileName);

    }

    [ HttpPost ]

    [ Route ( "api/ImageAPI/GetFiles" )]

public HttpResponseMessage GetFiles()

    {

string path = HttpContext .Current.Server.MapPath( "~/Uploads/" );

//Fetch the Epitome Files.

List < cord > images = new Listing < string >();

//Extract only the File Names to save information.

foreach ( cord file in Directory .GetFiles(path))

        {

            images.Add( Path .GetFileName(file));

        }

render Request.CreateResponse( HttpStatusCode .OK, images);

    }

}

View

The View consists of a Grade with an HTML FileUpload element and a Push button. Below the Course there's an HTML5 Progress element for displaying the progress of the uploading File.

There's also an HTML Tabular array which will be used to display the Listing of uploaded files.

Uploading Paradigm File

The Upload Button has been assigned a jQuery Click event handler. When the Button is clicked, the Image File is read from the HTML FileUpload element and added to an HTML5 FormData JavaScript object and and so the Epitome File is uploaded using XmlHttpRequest (XHR).

A Progress effect handler is attached to the XmlHttpRequest (XHR), which displays the progress of the Paradigm File being uploaded using the HTML5 Progress element.

Finally, the received Name and uploaded Image File is displayed in the HTML Table.

Getting List of Files

Inside the jQuery document ready event handler, the Web API Activeness method GetFiles is called and a loop is executed over the received Paradigm Files.

Within the loop, the Name and the actual Image File is displayed in HTML Table.

@{

    Layout = null ;

}

< !DOCTYPE html >

< html >

< head >

< meta proper name ="viewport" content ="width=device-width" />

< title > Alphabetize </ title >

</ head >

< trunk >

< course enctype ="multipart/form-data">

< input type ="file" id ="file" />

< input type ="push" id ="btnUpload" value ="Upload" />

</ form >

< progress id ="fileProgress" manner =" brandish : none"></ progress >

< 60 minutes />

< tabular array id ="tblImages" cellpadding ="0" cellspacing ="0">

< tr >

< thursday fashion =" width : 120px"> Paradigm Name </ th >

< thursday style =" width : 80px"> Image </ thursday >

</ tr >

< tr >

< td ></ td >

< td ></ td >

</ tr >

</ table >

< script blazon ="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/ane.eight.3/jquery.min.js"></ script >

< script type ="text/javascript">

        $( role (){

            GetFiles();

        });

function GetFiles() {

            $.ajax({

                type: "POST" ,

                url: "/api/ImageAPI/GetFiles" ,

                data: '{}' ,

                contentType: "awarding/json; charset=utf-viii" ,

                dataType: "json" ,

                success: function (files) {

                    $.each(files, function () {

                        AppendRow( this );

                    });

                },

                failure: function (r) {

                    alert(r.d);

                },

                mistake: function (r) {

                    alarm(r.d);

                }

            });

        };

part AppendRow(name) {

var row = $( "#tblImages tbody tr:terminal-child" );

//Remove if the row is dummy row.

if (row.find( "td:empty" ).length > 0) {

                row.remove();

            }

            row = row.clone();

            $( "td" , row).eq(0).text(proper noun);

            $( "td" , row).eq(1).html( "" );

var img = $( "<img />" );

            img.attr( "src" , ' @ Url.Content( "~/Uploads/" ) ' + name);

            img.attr( "mode" , "height:80px;width:80px" );

            $( "td" , row).eq(one).append(img);

            $( "#tblImages tbody" ).append(row);

        };

        $( "torso" ).on( "click" , "#btnUpload" , office () {

var formData = new FormData();

            formData.append( "file" , $( "#file" )[0].files[0]);

            $.ajax({

                url: '/api/ImageAPI/UploadFiles' ,

                type: 'POST' ,

                data: formData,

                cache: false ,

                contentType: false ,

                processData: imitation ,

                success: function (fileName) {

                    $( "#fileProgress" ).hide();

                     AppendRow(fileName);

                },

                xhr: part () {

var fileXhr = $.ajaxSettings.xhr();

if (fileXhr.upload) {

                        $( "progress" ).prove();

                        fileXhr.upload.addEventListener( "progress" , office (e) {

if (east.lengthComputable) {

                                $( "#fileProgress" ).attr({

                                    value: due east.loaded,

                                    max: due east.total

                                });

                            }

                        }, false );

                    }

render fileXhr;

                }

            });

        });

</ script >

</ body >

</ html >

Screenshot

Web API: Save (Upload) image to Server in ASP.Net MVC

Browser Compatibility

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

Internet Explorer FireFox Chrome Safari Opera

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

Downloads