Telerik blogs

For file uploads, Telerik UI for Blazor offers a powerful combination of ease-of-use and dependability, making it a fantastic solution for any Blazor developer.

About Blazor

Microsoft’s Blazor is an innovative web development framework developed as a component of the .NET ecosystem. This ecosystem is comprised of a wide variety of tools and libraries that are used in the process of creating software.

This framework distinguishes itself from the competition because it allows developers to create client-side logic, often known as the code inside the user’s web browser, using C#, a widely used and highly effective programming language typically reserved for server-side development.

The fact that developers can construct interactive user interfaces with Blazor using C#, HTML and CSS sets it apart from other platforms. This novel approach is driving its fast-expanding appeal among various .NET developers.

Telerik UI for Blazor

Progress Telerik UI for Blazor, a further enhancement of this new platform, effectively alters the software development experience by providing comprehensive tools with 100+ truly native, easy-to-customize Blazor components, that may significantly enhance productivity and simplify the process to a much greater extent. By integrating Telerik UI with Blazor, we can use additional functionality and construct highly effective and dynamic online apps more quickly.

For example, it features an InputFile component that simplifies reading data from browser files using .NET code. This component renders an HTML <input> element with the file type. Users are allowed to pick individual files by default. The addition of multiple properties, on the other hand, enables users to upload several files simultaneously. It may be beneficial when uploading PDF files, among other file kinds.

In addition, Telerik UI for Blazor works perfectly with the built-in security mechanisms and file size constraints included in Blazor, which helps avoid difficulties with both performance and security. Because of this, software developers are free to concentrate more on the logic and functionality of the programs they create rather than fretting about the possibility of performance issues or security risks.

Using Telerik UI for Blazor, here is an example of how to accomplish multiple file uploads:

<TelerikUpload  SaveUrl="https://my-app.com/api/Upload/Save"
  RemoveUrl="https://my-app.com/api/Upload/Remove"
  AutoUpload="true"
  Multiple="true" />

In this demonstration, the SaveUrl variable links to the method on your server that is used to save the files, and the RemoveUrl variable corresponds to the method used to delete files. When users pick files, the upload will begin immediately if the AutoUpload setting has been set to true, and users can upload multiple files if the Multiple setting has been set to true.

Saving Images and Resizing

First, add a reference to System.Drawing.Common to your project:

dotnet add package System.Drawing.Common

Then, the contents of your.razor file ought to resemble something like this:

@using Telerik.Blazor.Components
@using Telerik.Blazor.Input
@using System.Drawing
@using System.Drawing.Imaging
@using System.IO

<TelerikUpload OnSelect="@OnSelectHandler" 
OnRemove="@OnRemoveHandler" 
AutoUpload="true" 
AllowedExtensions="new string[]{ ‘.jpg’, ‘.jpeg’, ‘.png’ }" 
MaxFileSize="2097152"></TelerikUpload>

@code {
    private static readonly string ImageDirectory = Path.Combine(Directory.GetCurrentDirectory(), "images");
    
    async Task OnSelectHandler(IList<IFileFromBlazor> files)
    {
        try
        {
            foreach (var file in files)
            {
                string path = Path.Combine(ImageDirectory, file.Name);
                EnsureDirectoryExists(path);

                using (var memoryStream = new MemoryStream())
                {
                    await file.WriteToStreamAsync(memoryStream);

                    using (var originalImage = new Bitmap(memoryStream))
                    {
                        var newImage = ResizeImage(originalImage, 1024, 1024);

                        newImage.Save(path, GetImageFormat(file.Name));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // Add error handling code here.
            // ex.Message contains the description of the error.
        }
    }

    async Task OnRemoveHandler(IFileFromBlazor file)
    {
        try
        {
            string path = Path.Combine(ImageDirectory, file.Name);
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }
        catch (Exception ex)
        {
            // Add error handling code here.
            // ex.Message contains the description of the error.
        }
    }

    private static ImageFormat GetImageFormat(string fileName)
    {
        var extension = Path.GetExtension(fileName);
        switch (extension.ToLower())
        {
            case ".jpg", ".jpeg":
                return ImageFormat.Jpeg;
            case ".png":
                return ImageFormat.Png;
            default:
                throw new NotSupportedException("File extension is not supported");
        }
    }

    private static void EnsureDirectoryExists(string filePath)
    {
        string directory = Path.GetDirectoryName(filePath);
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
    }

    private static Bitmap ResizeImage(Image originalImage, int maxWidth, int maxHeight)
    {
        var ratioX = (double)maxWidth / originalImage.Width;
        var ratioY = (double)maxHeight / originalImage.Height;
        var ratio = Math.Min(ratioX, ratioY);

        var newWidth = (int)(originalImage.Width * ratio);
        var newHeight = (int)(originalImage.Height * ratio);

        var newImage = new Bitmap(newWidth, newHeight);
        using (var graphics = Graphics.FromImage(newImage))
        {
            graphics.DrawImage(originalImage, 0, 0, newWidth, newHeight);
        }

        return newImage;
    }
}

Users can upload picture files using the.jpg, .jpeg and .png file extensions, and each submitted image is automatically scaled to meet a maximum width and height of 1024 pixels while preserving the image’s original aspect ratio. The file size limit for each photograph is a maximum of 2 MB.

Here’s a summary of what the main parts of the code do:

Telerik Upload Component

The user interface (UI) for uploading files is managed by the Upload component. When a user picks a file, the OnSelect event is triggered, and when a user deletes a file from the list, the OnRemove event is triggered. The user interaction triggers both of these events.

OnSelectHandler

When the OnSelect event is triggered, the OnSelectHandler function gets called. It will read the uploaded file, resize the picture while preserving the aspect ratio, and store it in a directory inside the root directory of your application called “images.” In addition, the function checks to see whether the directory exists; if it does not, it creates the directory. The catch block includes a remark placeholder for you to handle the exception as required. This error is captured and treated in the catch block if it happens during this process (for example, a lack of write rights or inadequate storage), and it is handled if an exception occurs during this process.

OnRemoveHandler

When the OnRemove event is triggered, the OnRemoveHandler function is called. When a file is deleted from the client side, the matching file on the server is also deleted from the images directory. The exception is caught and managed in the catch block, a placeholder for fundamental error handling code. The error is captured and handled in the catch block if an exception occurs during the deletion process (such as a missing file or a lack of rights).

GetImageFormat

This function is responsible for returning an instance of the appropriate ImageFormat class based on the file extension of the uploaded image.

EnsureDirectoryExists

This function will first determine whether the directory in which the picture is to be saved already exists, and, if it does not, it will then create the directory.

ResizeImage

This method accepts a picture and a set of dimensions as input, and it produces a new image that has been scaled to fit inside those parameters while preserving the aspect ratio of the original image. The new picture’s width and height are computed to ensure that they do not exceed the maximum values supplied, and the aspect ratio of the new image is kept the same as the original image’s aspect ratio.

Dive into Blazor

As you continue to educate yourself on Blazor and Telerik UI for Blazor, here are some recommendations to take into consideration:

Hands-on Learning

Putting new technology into practice is often the most effective method to learn about them. Think about constructing a basic application using Blazor and the Telerik UI for Blazor plugin. It might be a simple blog or an easy-to-use online application like a to-do list.

Follow https://demos.telerik.com/blazor-ui for demos and playgrounds.

Documentation

Microsoft’s official documentation for Blazor is thorough and user-friendly for novices. In addition, Telerik offers comprehensive documentation for its UI for Blazor. Utilize these resources to further your study and improve your comprehension.

Follow https://docs.telerik.com/blazor-ui/introduction for complete documentation.

Online Tutorials and Courses

You may study Blazor and Telerik UI for Blazor with the assistance of many online tutorials and courses. These resources include video lessons on YouTube, Coursera and Udemy.

If you currently have an active license, follow https://learn.telerik.com/ for training.

Community

Participate in online forums such as Stack Overflow, Reddit or the official community for the Blazor platform. Using these platforms, you can learn from other developers’ experiences, ask questions and share your work.

Follow the official forum from Telerik for Blazor at https://www.telerik.com/forums/blazor.

Stay Updated

Blazor and Telerik UI for Blazor are constantly developing. Every new release has improved or new components. Follow the appropriate blogs, forums and social media platforms to stay up to speed on the latest features and developments.

Follow the Telerik blog and stay tuned: https://www.telerik.com/blogs.

Conclusion

Working with file uploads in Telerik UI for Blazor is unquestionably beneficial. The Upload component has an easy-to-use interface that allows developers to integrate file-handling functionality into their applications simply.

Furthermore, Progress Telerik’s good reputation ensures the component’s dependability. They are well-known for providing robust, high-quality development tools. Telerik components are thoroughly tested and tuned to ensure performance and stability and be user-friendly.

Another advantage is the guarantee of regular upgrades. The components are updated with the newest web development trends and standards. That means that if you use Telerik UI for Blazor, you can expect regular upgrades that include new features, performance improvements and bug fixes, allowing your application to stay contemporary, safe and efficient.

Importantly, Telerik provides outstanding support services even to users of the product’s trial edition. It ensures that you may thoroughly explore and comprehend the capabilities of the components.

Finally, Telerik UI for Blazor for file uploads provides a powerful combination of ease-of-use, dependability and continuing support, making it a fantastic solution for any Blazor developer. If you haven’t already, I highly recommend getting a trial version of Telerik UI for Blazor to learn more about its capabilities and benefits for your projects. You get free support during the trial period, and Telerik has a legendary support team that can help you with your needs.

Try Now


About the Author

Jefferson S. Motta

Jefferson S. Motta is a senior software developer, IT consultant and system analyst from Brazil, developing in the .NET platform since 2011. Creator of www.Advocati.NET, since 1997, a CRM for Brazilian Law Firms. He enjoys being with family and petting his cats in his free time. You can follow him on LinkedIn and GitHub.

Related Posts

Comments

Comments are disabled in preview mode.