Preview a photo before upload in a Razor Page

When you upload a photo to your website, you want to see a preview before you click “save”. This discusses a simple way to temporarily upload a photo with ajax so as to make a seamless process that does not require your web page to be refreshed.

You can also preview your photo without temporarily uploading it. This second method is the preferred method because it allows you to resize the photo before upload. Please check this link.

Non-preferred method

Example for a .net core razor page

This example applies this ajax upload in the context of a .net core razor page. The ajax file posts to a separate “handler” in the same razor page. This is accomplished by adding ” &handler=Send” to the ajax url property querystring. An OnPostSend() method is added to the razor page code to process the ajax request.

This code assumes you have a folder on your server called Products/PhotosTemp that you can write to. Note also the anti-forgery token that was added to the form as a best practice. Change the url in the ajax script to use your domain name and add additional code where shown with the “…” to create a database table and actually add the form data and file to your records.

Be sure to scroll horizontally to see the long lines of code.

Demo.cshtml file

@page "/Products"
@model Users.Pages.demoModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Demo for previewing a photo</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous"></script>
    <script>
        $(document).ready(function () {
            $(document).on('change', '#Upload', function () {
                // get the form by id
                var formdata_el = document.getElementById("formdata");
                //get the id of the record to be edited
                var id = document.getElementById("ID").value;
                formdata = new FormData(formdata_el);
                // the file input element  id is "Upload"
                var property = document.getElementById("Upload");
                // ensure the image is not too large
                var image_size = property.size;
                if (image_size > 2000000) {
                    alert("image file size is too big");
                }
                else {
                    // send a post to upload to temporary file
                    $.ajax({
                        url: "/Products?id=" + id + "&handler=Send",
                        method: "Post",
                        data: formdata,
                        headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                        contentType: false,
                        cache: false,
                        processData: false,
                        beforeSend: function () {
                            $('#uploaded_image').html("<label class='text-success'>Image Uploading ...</label>");
                        },
                        success: function (result) {
                            $('#product_photo').attr('src', "/Products/PhotosTemp/" + result);
                            $('#uploaded_image').html("");
                        },
                        error: function () {
                            alert("error");
                        }
                    }); 

                } 
            });
        });
    </script>

</head>
<body>
    <h2>Upload a photo with Preview</h2>
    <form method="post" enctype="multipart/form-data" id="formdata">
        <input type="hidden" id="ID" value="@Model.ID" />
        <div>
            <label>Product Name</label>
            <input type="text" id="Name" value="@Model.Name" />
        </div>
     
        <!-- more fields-->
        <div>
            <label>Upload Photo</label>
            <input type="file" name="Upload" id="Upload" />
            <div>
                <img id="product_photo" />
            </div>
            <div id="uploaded_image"></div>
        </div> 
        <div> <input type="submit" value="Save" /></div>
       
        @Html.AntiForgeryToken()
    </form>
</body>
</html>

demo.cshtml.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Users.Pages
{
    public class demoModel : PageModel
    {
       private Microsoft.AspNetCore.Hosting.IWebHostEnvironment _environment;

        public demoModel( Microsoft.AspNetCore.Hosting.IWebHostEnvironment environment)
        {
            _environment = environment;
            // more variables
        }
        [BindProperty]
        public String ID { get; set; }
        [BindProperty]
        public String Name { get; set; }
        public async Task OnGetAsync(String id)
        {
            //  when page is loaded.  
            ID = id;
            return Page();
        }
        public async Task OnPostAsync()
        {
            // add code to save the photo 
            //........
            //delete photo from temp folder
            string sourceDirectory = Path.Combine(_environment.WebRootPath, "Products", "PhotosTemp");
            var files = Directory.EnumerateFiles(sourceDirectory, "*Product" + ID + "_*");
            foreach (string currentFile in files)
            {
                System.IO.File.Delete(currentFile);
            }
            return Page();
        }
        public IActionResult OnPostSend()
        {
            // used to upload the photo in a temporary folder so that it can be displayed before update.
            String fileName = "";
            string path = System.IO.Path.Combine(_environment.WebRootPath, "Products", "PhotosTemp");

            Microsoft.AspNetCore.Http.IFormFile Upload = Request.Form.Files[0];
            if (Upload != null)
            {
                fileName = "Product" + ID + "_" + System.IO.Path.GetFileName(Upload.FileName);
                using (System.IO.FileStream stream = new System.IO.FileStream(System.IO.Path.Combine(path, fileName), FileMode.Create))
                {
                    Upload.CopyTo(stream);
                }
            }
            return Content(fileName);
        }
    }
}

{{}}

Leave a Reply

Your email address will not be published. Required fields are marked *