Click here to Skip to main content
15,885,366 members
Articles / Web Development / ASP.NET / ASP.NET Core

JQuery Image Upload with Razor Pages

Rate me:
Please Sign up or sign in to vote.
2.85/5 (3 votes)
11 Jan 2018CPOL3 min read 21.7K   2   4
This is article shows you how to use JQuery/Dropzone to perform Image uploads in the new Razor Pages template.

Razor Pages is the cool new project template that Microsoft introduced recently as part of the asp.net stack. It is probably the simplest and most straightforward to work with amongst the other asp.net project templates.

Today I will show you how to perform basic jQuery image upload using Razor Pages and JQuery. You will see how easy it is do so.

For examples of image upload methods with jQuery and other tools, see this jQuery image and video upload documentation page by Cloudinary, uploading with Zurb, or Dropzone’s various implementations.

Prerequisites

Steps

First, let us create a directory for our project and also create a new Razor Pages project by running the following commands.

PowerShell
mkdir JqueryRazorImageUpload
cd JqueryRazorImageUpload
dotnet new razor

Now go ahead and restore the default packages.

PowerShell
dotnet restore

If it works, great. Now stop the application and create two new files in the Pages folder. ImageUpload.cshtml which is the Page View and ImageUpload.cshtml.cs which is the Page Model.

C#
//ImageUpload.cshtml.cs
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace jqueryRazorpagesSimpleFileUpload.Pages
{
    public class ImageUploadModel : PageModel
    {
        public void OnGetAsync()
        {
        }
    }
}


<!-- ImageUpload.cshtml-->
@page
@model ImageUploadModel
<h1>Image Upload Page </h1>

Now go to open the _Layout.cshtml and add your new page to the navigation bar. it should look something like this.

Razor
<div class="navbar-collapse collapse">
   <ul class="nav navbar-nav">
      ...
      <li>
        <a asp-page="/ImageUpload">Image Upload</a>
      </li>
  </ul>
</div>

While at it also add a Styles section at the top of your _Layout.cshtml file, just after the head closing tag.

Razor
<head>
  ...
  @RenderSection("Styles", required: false);
</head>

Now go ahead and run the application to reveal the default Razor Pages application. You should also find Image Upload on the navigation bar.

PowerShell
dotnet run

Well, so far we have only covered the basics of setting up Razor pages. Now for the real deal. How do we Upload our files to our Page Model?

Let's start by downloading dropzone here. Add the js and CSS file to the Js and CSS folders under wwwroot.

Now, reference the CSS and Js files on your Page View. The CSS at the top and the js at the bottom. Although truthfully this doesn't matter since the RenderSection helper would only place them at locations where they were declared but just to keep you mentally organized.

Razor
<!-- At the top of the file -->
@section Styles {
    <link rel="stylesheet" href="~/css/dropzone.css" />
}
<!-- At the bottom of the file -->
@section Scripts {
    <script src="~/lib/dropzone.js"></script>
}

First, let us modify our Page Model to handle our future uploads. Go ahead and add the following piece of code to ImageUpload.cshtml.cs

C#
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace jqueryRazorpagesSimpleFileUpload.Pages
{
    public class ImageUploadModel : PageModel
    {
        public void OnGetAsync()
        {
        }
        public async Task OnPostAsync(IFormFile image)
        {
            var path = Path.Combine(
                        Directory.GetCurrentDirectory(), "wwwroot/uploads",
                        image.FileName);
            var memory = new MemoryStream();
            using (var stream = new FileStream(path, FileMode.Create))
            {
                await image.CopyToAsync(stream);
            }
        }
    }
}

We have added a method to handle all image uploads to our Page Model. Now we can go ahead and tell our view how to upload the Images.

Now let us add our form and then modify it to use our JQuery plugin.

Razor
<h1>Image upload page</h1>
<hr />
<div class="row">
    <div class="col-md-12">
        <h2>Upload Image</h2>
        <form method="post" enctype="multipart/form-data">
            <div class="form-group">
                <input name="image" type="file" class="form-control" accept="image/*"/>
            </div>
            <input type="submit" value="Upload" class="btn btn-default" />
        </form>
    </div>
</div>

As it is right now, our application is fully capable of handling our images but what we want is to upload our images using JQuery. So let us start by modifying our form by adding dropzone support.

<form method="post" enctype="multipart/form-data" id="imageUploadForm" class="dropzone">
    <div class="fallback">
            <div class="form-group">
            <input name="image" type="file" class="form-control" accept="image/*"/>
        </div>
            <input type="submit" value="Upload" class="btn btn-default" />
    </div>
</form>

All we need for Dropzone to work is add the class todropzone the form but in cases where Js is not available, we want our original form to act as a fallback. Awesome right. Right now Dropzone doesn't have enough information to work with, So at the bottom of our page, where we have our Scripts section, let's add some code for our image upload to function.

JavaScript
@section Scripts {
...
<script>
    $("#imageUploadForm").dropzone({ 
        url: "/imageupload",
        paramName: "image", 
        acceptedFiles: "image/*"
    });
</script>
}

With this, our application is good to go. Go ahead and run your application and try it out. Cool right?

One more thing

Now we are done with our JQuery image upload and It's working, but what if we want to display the most recently uploaded image. There are only two simple steps to achieve this. Add the piece of code below right below the div with a class of row.

Razor
<div class="row">
    <div class="col-sm-12">
        <h3>Recent Upload</h3>

        <div>
            <img id="recentImage" class="img-responsive img-thumbnail" width="500"/>
        </div>
    </div>
</div>

Now update the JS section to handle Image uploads for files successfully uploaded to the server.

JavaScript
<script>
    $("#imageUploadForm").dropzone({ 
        url: "/imageupload",
        paramName: "image", 
        acceptedFiles: "image/*",
        success: function(file){
            $("#recentImage").attr('src', `./uploads/${file.name}`);
        }
    });
</script>

Now that we have come to this point, there's quite a lot of changes we have made to our View file. So below find the completed View code with all the changes we have made so far.

Razor
@page 
@model ImageUploadModel 
@{ 
    ViewData["Title"] = "Image Uploader"; 
}
@section Styles {
    <link rel="stylesheet" href="~/css/dropzone.css" />
}
<h1>Image upload page</h1>
<hr />
<div class="row">
    <div class="col-md-12">
        <h2>Upload Image</h2>
        <form method="post" enctype="multipart/form-data" id="imageUploadForm" class="dropzone">
            <div class="fallback">
                 <div class="form-group">
                    <input name="image" type="file" class="form-control" accept="image/*"/>
                </div>
                 <input type="submit" value="Upload" class="btn btn-default" />
            </div>
        </form>
    </div>

</div>
<div class="row">
    <div class="col-sm-12">
        <h3>Recent Upload</h3>

        <div>
            <img id="recentImage" class="img-responsive img-thumbnail" width="500"/>
        </div>
    </div>
</div>
@section Scripts {
    <script src="~/lib/dropzone.js"></script>
    <script>
        $("#imageUploadForm").dropzone({ 
            url: "/imageupload",
            paramName: "image", 
            acceptedFiles: "image/*",
            success: function(file){
                $("#recentImage").attr('src', `./uploads/${file.name}`);
            }
        });
    </script>
}

Here's what the final app should look like:
Screenshot

Conclusion

Thanks for sticking around. Here’s a link to the GitHub repo for the codes. I hope you learned something new. Please share and leave a comment for any reason you feel like it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Nigeria Nigeria
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionMessage Closed Pin
6-Dec-20 21:52
Member 150140516-Dec-20 21:52 
Praiseyour code works like charm. Pin
Member 110878042-Sep-20 17:55
Member 110878042-Sep-20 17:55 
Praisepromoocodes Pin
James Zordan24-Apr-19 21:21
James Zordan24-Apr-19 21:21 
QuestionAdd Image snapshot Pin
Saineshwar Bageri4-Jan-18 19:32
Saineshwar Bageri4-Jan-18 19:32 
There are not image which show how JQuery Image Upload look like.
AnswerRe: Add Image snapshot Pin
Chilezie Reginald Unachukwu11-Jan-18 20:51
professionalChilezie Reginald Unachukwu11-Jan-18 20:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.