Uploading Images to Your .NET Server Using Froala WYSIWYG Editor? Here’s a Complete Guide

This article is sponsored by Froala.

Tweet
Share
WhatsApp

In today’s digital world, everyone wants to capture the moments they live. Whether it’s about catching the rays of sunshine bringing new hope and inspiration or sharing life’s best moments on social media, capturing images has become an integral part of our daily lives. 

Not only individuals but businesses are also making the most of images. From promoting products and services to attracting customers, generating new leads, measuring conversions, and developing success-driven strategies, every aspect benefits from stunning images. So, all in all, millions of images are being captured and uploaded on the web every day.  Just pick up your camera and take an image from any possible angle. It’s as simple as that.  

Is this all set to go? No.  

A big slice of the credit goes to convenient user interfaces that make uploading images to the dedicated platforms and servers easy. From a developer’s point of view, one of the most complex situations is when they have to upload images to a web app, platform, or specific server. The primary reason is that different platforms or servers have different prerequisites, and they have to learn everything before proceeding. 

On top of all that, one commonly known problem that developers often face is “how to upload images to a .Net server” with less coding effort and time. If you’re one of them, let’s go ahead and learn everything about it. 

What Is Froala Editor?

You might be thinking we’re going off-topic discussing Froala Editor, but we must discuss it to initiate the uploading process because it is the backbone of a smooth uploading process. 

By definition, Froala Editor is a WYSIWYG editor that enables rich-text editing capabilities for your application. However,  in contrast to other editors, it says, “what you see is what you get.” 

Our main objective in discussing Froala Editor here is enabling you to use it to upload images to the .Net server. You literally don’t need to do any coding with Froala when uploading images; its beautiful features and 30 out-of-the-box plugins will do magic. 

Image source: Froala 

As Froala supports many tech stacks you might be using or want to use to upload images in the future, it will resolve all of your tech stack-related hurdles in one go. 

So it’s easy to see that Froala is always an excellent choice to upload images and files. 

Can I Use Froala to Upload Images and Files to My Server?

Of course, you can. Why not?  

When you get to know its jaw-dropping features, you’ll fall in love with it. 

Without wasting more time, let’s jump into the features of Froala that make it an iconic choice to use for uploading images and files to your server. 

Fast

Imagine the moment when you upload an image or file to your server, and it quickly reflects on the screen as an output. Froala makes it happen! It saves and reflects changes as fast as the blink of an eye.   

Developer friendly

Whether you’re a new developer or have years of experience using .Net server, you always need specific API documentation that makes your work less frustrating. Froala WYSIWYG Editor is created with this in mind. 

Easy to customize and extend 

Love customization? You can do anything with the Froala Editor while uploading images and files because its well-structured and documented code is clear to understand and extend.

Easy to integrate 

Froala is also easy to integrate with any kind of project. It requires only basic JavaScript and HTML coding, then you are all set to go. 

Out-of-the-box plugins

There’s no need to spin the wheel. With its stunning ready-to-go plugins to upload images and files, the Froala WYSIWYG Editor changes the game by providing you with a plethora of opportunities to upload images and files successfully.  

Classic and inline

Many traditional editors don’t let you transform a JavaScript tool into an essential technology, but the Froala WYSIWYG HTML Editor works wonders with a ton of next-generation editing abilities that make it classic and inline. 

Secure

From a security perspective, there is no doubt that Froala WYSIWYG HTML Editor is bulletproof. You don’t have to worry about any security concerns such as file-size or file-access attacks that are often encountered while uploading an image. 

So you’ve familiarized yourself with the features of Froala. Now it’s time to discuss how to upload images and files to a .Net server using Froala’s WYSIWYG Editor. 

Are you ready? 

Give us a high five, and let’s get started! 👋

Step-by-Step Guide on Uploading Images to .Net Server Using WYSIWYG Editor

To successfully upload an image to your .Net server, you need to perform the three steps described below.

  • Initialize the JavaScript editor
  • Receive the uploaded image and store it
  • Return the path to the uploaded image

Let’s discuss these steps in detail now! 

Step 1: Initialize the JavaScript editor

To initiate the process, you have to set the imageUploadURL option to the URL where you want to upload the images. 

One exciting thing you will love about the WYSIWYG HTML editor is that you can set the options like imageUploadMethod,  imageAllowedTypes, imageUploadParam, imageMaxSize, and imageUploadParams based on how you want to upload an image and receive it by the .Net server. 

Note: As per your preference, you can set imageAllowedTypes, imageUploadParam, imageMaxSize, imageUploadParams, and imageUploadMethod within the initialization process.

<script>
  new FroalaEditor(‘.selector’, {
    // Set the image upload URL.
    imageUploadURL: ‘/FroalaApi/UploadImage’
  })
</script>

Step 2: Receive the uploaded image and store it

The server implementation is accountable for receiving the request and handling it effectively. In .Net, the uploaded image is available in the HttpContext global variable. The .Net editor SDK is designed to detect the uploaded image automatically, so you just have to specify the path to where to store it.

Note: You have to ensure that the path of the image is related to the root of the project, such as: 

string uploadPath = “/Public/”;
object response = FroalaEditor.string uploadPath = “/Public/”;
object response = FroalaEditor.Image.Upload(System.Web.HttpContext.Current, uploadPath);.Upload(System.Web.HttpContext.Current, uploadPath);

One important thing to keep an eye on is that the server must have written permissions to the uploaded image folder for the image to be saved appropriately.  

You should also make sure that the image you’ve uploaded is public and viewable in your browser so that your audience can view it.

Step 3: Return the path to the uploaded image

The SDK generates an ImageResponse object containing the absolute path of the uploaded image if the save action is successful, so your server only needs to return it to the client.

return Json(response);

Let’s have a look at the complete example of the entire process. 

<script>
  new FroalaEditor(‘.selector’, {
    // Set the image upload URL.
    imageUploadURL: ‘/FroalaApi/UploadImage’
  })
</script>
using System;
using System.Web.Mvc;

namespace demo.Controllers
{
    public class FroalaApiController : Controller
    {
        public ActionResult UploadImage()
        {
            string uploadPath = “/Public/”;

            try
            {
                return Json(FroalaEditor.Image.Upload(System.Web.HttpContext.Current, uploadPath));
            }
            catch (Exception e)
            {
                return Json(e);
            }
        }
    }
}

Congratulations! You’ve successfully uploaded the image to the .Net server 🎊

Now, one question might be troubling you: If you want to delete, validate, and resize this image, then would you be able to do it?

The answer is yes because the Froala WYSIWYG Editor is also a blessing for this purpose. 

Let’s see how! 

Step-by-Step Guide on Deleting Image Using Froala WYSIWYG Editor

To delete an image using the Froala WYSIWYG Editor, you must perform the three steps below. 

  • Intercept image being removed
  • Send a request to the server
  • Delete the image

Why wait? Let’s move to the next exciting section of this article. 

Step 1: Intercept image being removed

When an image is removed from the JavaScript editor, it triggers two main events: froalaEditor.image.beforeRemove and froalaEditor.image.removed

You can use either of the options to delete the image from the server based on your preference. However, we suggest going with the latter one because, at that point, you will be sure that the image is removed from the editable area.

Step 2: Send request to the server

Although there is no built-in feature for sending a request to the server, it is simple to do with an AJAX request. 

Use the below code and proceed with this process 👇

<script>
  // Catch the image being removed.
  var editor = new FroalaEditor(‘.selector’);

  editor.opts.events[‘image.removed’] = function (e, editor, $img) {
    $.ajax({
      // Request method.
      method: ‘POST’,

      // Request URL.
      url: ‘/FroalaApi/DeleteImage’,

      // Request params.
      data: {
        src: $img.attr(‘src’)
      }
    })
    .done (function (data) {
      console.log (‘Image was deleted’);
    })
    .fail (function (err) {
      console.log (‘Image delete problem: ‘ + JSON.stringify(err));
    })
  }
</script>

Step 3: Delete the image

The server implementation is accountable for receiving the request and handling it effectively. Using the code from the previous step, you have to make the image path available in the HttpContext global variable. 

The FroalaEditor.Image.Delete() method from the .Net SDK will expect the path of the image to be removed from the disk.

Note: The path of the image must be related to the root of the project, such as: 

FroalaEditor.Image.Delete(“/Public/” + HttpContext.Request.Form[“src”]);

Let’s have a look at the complete example. 

<script>
  // Catch the image being removed.
  var editor = new FroalaEditor(‘.selector’);

  editor.opts.events[‘image.removed’] = function (e, editor, $img) {
    $.ajax({
      // Request method.
      method: ‘POST’,

      // Request URL.
      url: ‘/FroalaApi/DeleteImage’,

      // Request params.
      data: {
        src: $img.attr(‘src’)
      }
    })
    .done (function (data) {
      console.log (‘Image was deleted’);
    })
    .fail (function (err) {
      console.log (‘Image delete problem: ‘ + JSON.stringify(err));
    })
  }
</script>
using System;
using System.Web.Mvc;

namespace demo.Controllers
{
    public class FroalaApiController : Controller
    {
        public ActionResult DeleteImage()
        {
            try
            {
                FroalaEditor.Image.Delete(“/Public/” + HttpContext.Request.Form[“src”]);
                return Json(true);
            }
            catch (Exception e)
            {
                return Json(e);
            }
        }
    }
}

This way, you can successfully delete an uploaded image from your .Net server using Froala WYSIWYG editor. 

Apart from deleting an image, what if you want to validate the format or resize it? Froala WYSIWYG Editor helps you do this too. Let’s find out how. 

Step-by-Step Guide on Validating Image Using Froala WYSIWYG Editor 

The image-validation process consists of two stages. 

  • Validate extensions
  • Custom validation 

Let’s find out how it works. 

Step 1: Validate extension

WYSIWYG editor’s .Net SDK will check the image extension when it is being saved to the disk. For accuracy, it uses the mime type of the file in addition to the file name extension. Here’s an example of the code you need to perform to validate an image in your .Net server. 

FroalaEditor.ImageOptions options = new FroalaEditor.ImageOptions
{
    Fieldname = “file”,
    Validation = new FroalaEditor.ImageValidation(new string[] { “gif”, “jpeg”, “jpg”, “png”, “svg”, “blob” }, new string[] { “image/gif”, “image/jpeg”, “image/pjpeg”, “image/x-png”, “image/png”, “image/svg+xml” })
};

object response = FroalaEditor.Image.Upload(System.Web.HttpContext.Current, fileRoute, options);

Step 2: Custom validation

Instead of validating the extension and mime type, you can also use a custom method. This will provide you with complete choice over the types of image formats you want to save to your hard drive.

Below, we’ve explained the example of an image in square format. Let’s have a look.  

Func validationFunction = (filePath, mimeType) => {

    MagickImageInfo info = new MagickImageInfo(filePath);

    if (info.Width != info.Height)
    {
        return false;
    }

    return true;
};

FroalaEditor.ImageOptions options = new FroalaEditor.ImageOptions
{
    Fieldname = “file”,
    Validation = new FroalaEditor.ImageValidation(validationFunction)
};


var image = new FroalaEditor.Image(System.Web.HttpContext.Current);
object response = image.Upload(fileRoute, options);

Here is a complete example of the whole image validation process. 

<script>
  new FroalaEditor(‘.selector’, {
    // Set the image upload URL.
    imageUploadURL: ‘/FroalaApi/UploadImageValidation’
  })
</script>
using System;
using System.Web.Mvc;

namespace demo.Controllers
{
    public class FroalaApiController : Controller
    {
        public ActionResult UploadImageValidation()
        {
            string fileRoute = “/Public/”;

            FroalaEditor.ImageOptions options = new FroalaEditor.ImageOptions
            {
                Fieldname = “file”,
                Validation = new FroalaEditor.ImageValidation(new string[] { “gif”, “jpeg”, “jpg”, “png”, “svg”, “blob” }, new string[] { “image/gif”, “image/jpeg”, “image/pjpeg”, “image/x-png”, “image/png”, “image/svg+xml” })
            };

            try
            {
                return Json(FroalaEditor.Image.Upload(System.Web.HttpContext.Current, fileRoute, options));
            }
            catch (Exception e)
            {
                return Json(e);
            }
        }
    }
}

Step-by-Step Guide on Resizing an Image Using Froala WYSIWYG Editor 

As we said earlier,  the Froala WYSIWYG Editor allows you to resize the image you’ve uploaded to your .Net server. 

Let’s take a look at the steps. 

Resize image 

You can resize the image’s width and height displayed in the browser by changing it. 

Note: You’ll not be able to resize the image’s physical size. It will be done on the server side only.

Here is the image-resize process, where the Froala WYSIWYG Editor is using the .Net MagickImage.Resize method. Let’s have a look. 

MagickGeometry resizeGeometry = new MagickGeometry(300, 300);
resizeGeometry.IgnoreAspectRatio = true;

FroalaEditor.ImageOptions options = new FroalaEditor.ImageOptions
{
    ResizeGeometry = resizeGeometry
};

object response = FroalaEditor.Image.Upload(System.Web.HttpContext.Current, fileRoute, options);

Here is the complete example of the whole image-resize process. 

<script>
  new FroalaEditor(‘.selector’, {
    // Set the image upload URL.
    imageUploadURL: ‘/FroalaApi/UploadImageResize’,

    imageUploadParams: {
      id: ‘my_editor’
    }
  })
</script>
using System;
using System.Web.Mvc;
using ImageMagick;

namespace demo.Controllers
{
    public class FroalaApiController : Controller
    {
        public ActionResult UploadImageResize()
        {
            string fileRoute = “/Public/”;

            MagickGeometry resizeGeometry = new MagickGeometry(300, 300);
            resizeGeometry.IgnoreAspectRatio = true;

            FroalaEditor.ImageOptions options = new FroalaEditor.ImageOptions
            {
                ResizeGeometry = resizeGeometry
            };

            try
            {
                return Json(FroalaEditor.Image.Upload(System.Web.HttpContext.Current, fileRoute, options));
            }
            catch (Exception e)
            {
                return Json(e);
            }
        }
    }
}

So far, we’ve discussed how to upload, delete, validate, and resize an image in your .Net server using the WYSIWYG editor. 

You might be wondering what the steps would be to upload a file rather than a single image to the server. 

For this purpose, we’ve curated a guide on uploading files to the .Net server using the WYSIWYG editor. Let’s jump to that. 

Step-by-Step Guide on Uploading Files to .Net server Using WYSIWYG Editor

Following the three main steps listed below will enable a successful file-uploading process:

  • Initialize the JavaScript editor
  • Receive the uploaded file and store it
  • Return the path to the uploaded file

Step 1: Initialize the JavaScript editor

The first and foremost thing is to make sure you set the fileUploadURL option to the URL where you want to upload the files, just like you did in the image-uploading process earlier. 

Note: You can set other options such as fileUploadParam, fileUploadParams, fileUploadMethod, fileMaxSize, and fileAllowedTypes based on how you want to upload files on the server. 

<script>
  new FroalaEditor(‘.selector’, {
    // Set the file upload URL.
    fileUploadURL: ‘/FroalaApi/UploadFile’
  })
</script>

Step 2: Receive the uploaded file and store it

The server implementation is responsible for receiving the request and handling it. 

The uploaded file is stored in the HttpContext global variable in .Net. The .Net editor SDK is designed to recognize the uploaded file automatically, so all you have to do is indicate the directory where it should be saved.

Note: The path of the file again must be related to the root of the project, such as: 

string uploadPath = “/Public/”;
object response = FroalaEditor.File.Upload(System.Web.HttpContext.Current, uploadPath);

The server must have written permissions in the uploads folder for the uploaded file to be saved appropriately. 

You should also make sure that the uploaded file is publicly accessible in your browser so that your users can view it.

Step 3: Return the path to the uploaded file

If the save action is completed successfully, the SDK will generate a FileResponse object with the absolute path to the uploaded file, so your server just has to return it to the client side.

return Json(response);

Here is the complete example of the entire file-uploading process. 

<script>
  new FroalaEditor(‘.selector’, {
    // Set the file upload URL.
    fileUploadURL: ‘/FroalaApi/UploadFile’
  })
</script>
using System;
using System.Web.Mvc;

namespace demo.Controllers
{
    public class FroalaApiController : Controller
    {
        public ActionResult UploadFile()
        {
            string uploadPath = “/Public/”;

            try
            {
                return Json(FroalaEditor.File.Upload(System.Web.HttpContext.Current, uploadPath));
            }
            catch (Exception e)
            {
                return Json(e);
            }
        }
    }
}

Wow! You’ve learned how to upload a file. Great. 

If you want to learn how to delete this file, keep reading. 

Step-by-Step Guide on Deleting File from Server Using Froala WYSIWYG Editor

By implementing the three steps below, you’ll be able to delete a file from your .Net server using the WYSIWYG editor with less time and effort. 

  • Intercept file being removed
  • Send request to the server
  • Delete the file

Step 1: Intercept file being removed

As we said earlier, two events are triggered when a file is removed from the JavaScript editor: froalaEditor.file.beforeRemove and froalaEditor.file.removed

You can delete the file from the server using either of these methods, but we suggest the latter one because, at that point, you will be sure that the file is removed from the editable area. 

Step 2: Send request to the server

Although there is no built-in feature for sending a request to the server, it is simple to do so with an AJAX request.

<script>
  // Catch the file being removed.
  var editor = new FroalaEditor(‘selector’);

  editor.opts.events[‘file.unlink’] = function (e, editor, file) {
    $.ajax({
      // Request method.
      method: ‘POST’,

      // Request URL.
      url: ‘/FroalaApi/DeleteFile’,

      // Request params.
      data: {
        src: file.getAttribute(‘href’)
      }
    })
    .done (function (data) {
      console.log (‘File was deleted’);
    })
    .fail (function (err) {
      console.log (‘File delete problem: ‘ + JSON.stringify(err));
    })
  }
</script>

Step 3: Delete the file

Receiving the request and effectively managing it are the responsibility of the server implementation. The file path is available in the HttpContext global variable, thanks to the code from the previous step. 

The FroalaEditor.File.Delete() method from the .Net SDK is expecting the file path to be removed from the disk.

Note: The path of the file again must be related to the project’s root, such as: 

FroalaEditor.File.Delete(“/Public/” + HttpContext.Request.Form[“src”]);

Here is a complete example of the entire process. 

<script>
  // Catch the file being removed.
  var editor = new FroalaEditor(‘selector’);

  editor.opts.events[‘file.unlink’] = function (e, editor, file) {
    $.ajax({
      // Request method.
      method: ‘POST’,

      // Request URL.
      url: ‘/FroalaApi/DeleteFile’,

      // Request params.
      data: {
        src: file.getAttribute(‘href’)
      }
    })
    .done (function (data) {
      console.log (‘File was deleted’);
    })
    .fail (function (err) {
      console.log (‘File delete problem: ‘ + JSON.stringify(err));
    })
  }
</script>
using System;
using System.Web.Mvc;

namespace demo.Controllers
{
    public class FroalaApiController : Controller
    {
        public ActionResult DeleteImage()
        {
            try
            {
                FroalaEditor.File.Delete(“/Public/” + HttpContext.Request.Form[“src”]);
            }
            catch (Exception e)
            {
                return Json(e);
            }
        }
    }
}

So will you try uploading files to and deleting files from your .Net server using WYSIWYG editor? Give it a chance once! You’ll learn something new. 

Looking forward, a question might be going through your mind: Does Froala editor enable you to save images and files to Amazon S3? 

Let’s find out below 👇

Does Froala Support Saving Images and Files on Amazon S3?

Yes, absolutely! 

As we said at the beginning of the article, the Froala WYSIWYG editor is written in JavaScript, enabling rich-text editing capabilities for your applications. 

Below, we’ve curated a guide on this as well. If you’re interested in saving files this way, please follow it. 

To start the process, you need to follow the four steps listed below. 

  • Create an S3 bucket
  • Set CORS on the S3 bucket
  • Compute signature
  • Initialize the Javascript editor

Let’s get started!

Step 1: Create an S3 bucket

First of all, create an S3 bucket. You can refer to the dedicated documentation from Amazon on how to create an S3 bucket

If you have any difficulties creating it, please contact Amazon for assistance.

Step 2: Set CORS on the S3 bucket

CORS (cross-origin resource sharing) primarily instructs Amazon on which domains to accept requests from and what kinds of requests to accept. Amazon Documentation has a full explanation of how this works. 

We recommend adding a configuration like the one below, where the ALLOWED URL is replaced with the page URL where the JavaScript editor is used. 

<?xml version=”1.0″ encoding=”UTF-8″?>
<CORSConfiguration xmlns=”http://s3.amazonaws.com/doc/2006-03-01/”>
    <CORSRule>
        <AllowedOrigin>ALLOWED_URL</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Step 3: Compute Signature

It is vital to compute a signature using the AWS access key ID and AWS secret access key and provide it with the upload request in order to get the image uploaded to S3. 

The .Net SDK for the rich-text editor includes methods for computing S3 signatures using the V4 signing algorithm, which works with buckets built on any of the S3 regions.

FroalaEditor.S3Config config = new FroalaEditor.S3Config
{
    // The name of your bucket.
    Bucket = ‘bucket-name’,

    // S3 region. If you are using the default us-east-1, this can be ignored.
    Region = ‘eu-west-1’,

    // The folder where to upload the images.
    KeyStart = ‘uploads’,

    // File access.
    Acl = ‘public-read’,

    // AWS keys.
    AccessKey = YOUR_AWS_ACCESS_KEY,
    SecretKey = YOUR_AWS_SECRET_KEY
};

// Compute the signature.
object s3Hash = FroalaEditor.S3.GetHash(config);

Step 4: Initialize the JavaScript editor

Don’t forget to set the imageUploadToS3 option on initialization to get images uploaded to Amazon S3 quickly with no hassle. The editor .Net SDK computes the hash needed for this as a response to the FroalaEditor.S3.GetHash method.

<script>
  $.get( “/FroalaApi/S3Signature”, {})
  .done(function( data ) {
      $(‘.selector’).froalaEditor({
          imageUploadToS3: data
      })
  });
</script>

So this is how you can save images and files uploaded to the .Net server on Amazon S3 using the Froala WYSIWYG Editor. 

Wrap Up

Finally, we’ve come to the end of our article. 

Hopefully, we’ve provided you with valuable tutorials and guides on how to upload images to your .Net server using Froala WYSIWYG editor while saving time and effort. Believe us, after reading and following the step-by-step guides, you’ll no longer find it difficult to upload, delete, resize/validate images to the .Net server.  You’ll undoubtedly be able to upload and handle images the way you want to. 

If you have any doubt about the above information, don’t hesitate. Write to us in the comments below. We’ll respond to you in the best way possible.  However, if you’ve ever tried this image-uploading process in your development career, then share your experience with us. Our readers will love to hear from you. 

Happy uploading! 

Stay tuned for more such posts. 

Partner Content

Partner Content

Fossbytes caters to a vast and influential readership spread all across the world. Get your brand in front of millions of readers with our specially-crafted and attractive sponsored posts. To learn more, read our sponsored post guidelines.
More From Fossbytes

Latest On Fossbytes

Find your dream job