Upload Files In .NET Core By Drag And Drop Using Dropzone.JS

17. October 2016 21:41

.NET Core ASP.NET MVC Jquery Web  0 Comments

Mostly all web applications out there has some way or the other amazing ways to upload a single or multiple files. While surfing on Github I found this amazing library to upload the files to the server in a unique way with lot of configurations. It support parallel uploads along with cancellation of the files which are in the upload queue along with a good looking progress bar to show the progress of upload.

I get the drag and drop to work in just like 5 minutes. It is super easy and that with some powerful configurations. To install Dropzone you can use the Nuget command.

PM> Install-Package dropzone
Add reference of js and css files on your page. To get the UI ready use this HTML.
<div class="row">
    <div class="col-md-9">
        <div id="dropzone">
            <form action="/Home/Upload" class="dropzone needsclick dz-clickable" id="uploader">
                <div class="dz-message needsclick">
                    Drop files here or click to upload.<br>
                </div>
            </form>
        </div>
    </div>
</div>

The output of the above HTML looks like this.

There are few points to be noted here in the above HTML. Notice the action and class attributes for the form element. You will also be needing the id attribute as well. Here the action attribute points to the ActionResult which is responsible to handle the file upload. I have pointed it to the Upload ActionResult in my controller class which accepts a parameter of type IFormFile. In case of a MVC application, we would have used HttpPostedFileBase class. Here is the complete code which handles the file upload.

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
    var uploads = Path.Combine(_environment.WebRootPath, "uploads");
    if (file.Length > 0)
    {
        using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
        {
            await file.CopyToAsync(fileStream);
        }
    }
    return RedirectToAction("Index");
}

The _environment variable you see in the above code is the instance of IHostingEnvironment interface which I have injected in the controller. Always use IHostingEnvironment interface to resolve the paths. You can hard code the file path but it may not work on other platforms. The combine method returns the correct path based on the platform the code is executing. The WebRootPath property returns the path of wwwroot folder and the second parameter uploads is then appended correctly with the path.

Now it is time to make some adjustment in the Dropzone configuration. Recall the id attribute of the form element. I named it uploader. The Dropzone library has a unique way to set the configuration. Like this.

<script>
    $(document).ready(function () {
        Dropzone.options.uploader = {
            paramName: "file",
            maxFilesize: 2,
            accept: function (file, done) {
                if (file.name == "test.jpg") {
                    alert("Can't upload a test file.");
                }
                else {
                    //Show a confirm alert and display the image on the page.
              }
           }
        };
});
</script>
You have to be a bit careful when setting this configuration. In the configuration above the paramName states the name that will be used to transfer the file. This name should be the same as the IFormFile parameter of the Upload method in the controller. In this case I am using file and the same has to be there in the param of the Upload method. If the names mis-match the files will not be uploaded. The other parameter I am using is the maxFileSize and is very much self-explanatory. I have set the size to be 2 MB and because of this configuration, any file above this limit will not be uploaded. Here is an example of such kind of failure.
All the other files were uploaded successfully except one file which is 4.32 MB and is way beyond the limit I set in my Dropzone configuration. If you hover the file, you will see why it got failed.
This is the simplest approach through which you can have drag and drop upload support in your applications. The configuration I am using here is the simplest and minimalistic configuration that can get you started in no time. There are some more powerful configurations like parallelUploads and uploadMultiple that you should look into and use it.
 No Rating

ASP.NET Postback Issue with Colorbox jQuery Plugin

19. August 2012 15:27

ASP.NET Jquery  1 Comment

Yesterday, while working on a project I came across a weird problem while working with Colorbox jquery plugin and ASP.NET. The problem is not only with Colorbox but also with another famous plugin called Fancybox. If you plan to use the plugine just to show dialog boxes, then this plugin works perfectly fine. Integrating the plugin with ASP.NET works fine but prevents post back if you have server controls on the colorbox dialog box (which is actually an invisible div on the page). ASP.NET developers can consider this as a bug but actually it's not a bug, but a scenario missed in the plugin.

I have a button click for button labelled Yes which redirects me to the about page. Now when you try to click the button there will be no post back event. This is because Colorbox renders the div outside the form tag which hinders the post back event.

Now to overcome this problem, you need to jump inside the Colorbox plugin code. The main function that add the content to the DOM or on the page is called appendHTML

function appendHTML() {
    if (!$box && document.body) {
        init = false;

        $window = $(window);
        $box = $tag(div).attr({ id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : '' }).hide();
        $overlay = $tag(div, "Overlay", isIE6 ? 'position:absolute' : '').hide();
        $wrap = $tag(div, "Wrapper");
        $content = $tag(div, "Content").append(
			$loaded = $tag(div, "LoadedContent", 'width:0; height:0; overflow:hidden'),
			$loadingOverlay = $tag(div, "LoadingOverlay").add($tag(div, "LoadingGraphic")),
			$title = $tag(div, "Title"),
			$current = $tag(div, "Current"),
			$next = $tag(div, "Next"),
			$prev = $tag(div, "Previous"),
			$slideshow = $tag(div, "Slideshow").bind(event_open, slideshow),
			$close = $tag(div, "Close")
		);

        $wrap.append( // The -1x3 Grid that makes up ColorBox
			$tag(div).append(
				$tag(div, "TopLeft"),
				$topBorder = $tag(div, "TopCenter"),
				$tag(div, "TopRight")
			),
			$tag(div, false, 'clear:left').append(
				$leftBorder = $tag(div, "MiddleLeft"),
				$content,
				$rightBorder = $tag(div, "MiddleRight")
			),
			$tag(div, false, 'clear:left').append(
				$tag(div, "BottomLeft"),
				$bottomBorder = $tag(div, "BottomCenter"),
				$tag(div, "BottomRight")
			)
		).find('div div').css({ 'float': 'left' });

        $loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none');

        $groupControls = $next.add($prev).add($current).add($slideshow);

        $(document.body).append($overlay, $box.append($wrap, $loadingBay));
    }
}

In the above method (which is an extract from the plugin), notice that the plugin is focusing on document.body whereas in order to get it working with the post back events we need to change the above highlighted lines with the one below:

if (!$box && document.forms[0]) {

And

$(document.forms[0]).append($overlay, $box.append($wrap, $loadingBay));

After the changes have been made, it's time to check again. Try clicking the button and check again. This time you will be redirected to the about page. Although, this seems to be simple problem, but there will be few fellow programmers who will scratch their head if they stuck in this sort of a problem. Hope this helps someone out there.

Currently rated 5.0 by 1 person

Infinite Scrolling In ASP.NET With jQuery

28. April 2012 12:53

ASP.NET Jquery T-SQL  5 Comments

I didn't create the whole solution by myself. The initial idea is from the All-In-One Code Framework sample. I was just customizing my BlogEngine and for one of the module I thought it would be nice not to use paging and I should go for infinite scrolling stuff. This idea seems cool to me and without wasting any time I just do a quick web search and I came across a solution which is a part of a All-In-One Code Framework. This was not the complete solution I was looking for but I can re-use the jQuery part in the sample.

Assembling jQuery Part

I just re-use the all jQuery script as it is without any major modification. The only change I made is the name of the web method in the url parameter of the Ajax method I have in page code behind and change the method name to InfiniteScroll:

function InfiniteScroll() {
    $('#divPostsLoader').html('<img src="images/loader.gif">');

    //send a query to server side to present new content
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetData",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (data != "") {
                $('.divLoadData:last').after(data.d);
            }
            $('#divPostsLoader').empty();
        }
    })
};

I already have 2 divs in the page where the data is being loaded when the user scrolls down at the bottom of the page. This is the simplest Ajax call written in jQuery and I assume you are aware of the syntax and methods and require no explanation. What I require here is to call this function when the user scrolls at the bottom of the page. So how to know when the user scrolls and reach at the bottom of the page? Here is the method which fires the InfiniteScroll() function:

$(window).scroll(function () {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        InfiniteScroll();
    }
});

Make sure you put the scroll function inside the document.ready function. Now when the user scrolls at the bottom of the page then it will call the InfiniteScroll() function which in turn loads new data in the divLoadData div.

The Code-Behind

In the code-behind create a WebMethod function that returns a HTML string. For this example I am loading all my blog posts title, post date and slug from my blog engine database which is a SQL Server CE 4.0. Here is the method:

[WebMethod]
public static string GetData()
{
    RecordCount = RecordCount + 10;
    string Sql = "SELECT Title, DateCreated, Slug FROM be_Posts ORDER BY Title OFFSET " + FirstCount + " ROWS FETCH NEXT 10 ROWS ONLY";
    FirstCount = RecordCount;
    StringBuilder sb = new StringBuilder();
    dt = new DataTable();
    da = new SqlCeDataAdapter(Sql, con);
    con.Open();
    da.Fill(dt);

    DataView dv = dt.DefaultView;

    foreach (DataRowView row in dv)
    {
        sb.AppendFormat("<p>Post Title" + " <strong>" + row["Title"] + "</strong>");
        sb.AppendFormat("<p>Post Date" + " <strong>" + row["DateCreated"] + "</strong>");
        sb.AppendFormat("<p>Slug" + " <strong>" + row["Slug"] + "</strong>");
        sb.AppendFormat("<hr/>");
    }

    sb.AppendFormat("<divstyle='height:15px;'></div>");
    con.Close();
    return sb.ToString();
}

Infinite scrolling is nothing but is a sort of automatic paging. Every time a user scrolls down at the bottom of the page, the query gets fired and gets the new set of data. As I am using SQL CE 4.0 the paging query is different than that of the SQL Server 2008.

Query for SQL CE 4.0:

SELECT Title, DateCreated, Slug FROM be_Posts ORDER BY Title OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY

Change the OFFSET and FETCH NEXT to get the next result set.

Query For SQL Server 2008:

SELECT Title, DateCreated, Slug FROM ( 
     SELECT 
          ROW_NUMBER() OVER (ORDER BY title) AS row, Title, DateCreated, Slug
     FROM be_Posts
) AS a WHERE row BETWEEN 1 AND 10

I have changed the query in the above code to get me the set of next results every time a user scrolls at the bottom of the page. When the user scrolls down I increment the FirstCount with 10 which is a value of RecordCount variable. I have attached the complete solution so you can try. I don't have the database included in the solution as it is my blog database. You have to create one to test it out.

Download: InfiniteScroll.zip (2.28 mb)

Currently rated 2.0 by 1 person

Awesome jQuery Image Plugins For Web Developers

22. April 2012 03:42

Jquery Web  0 Comments

I am not a web developer but still I love working with jQuery, CSS3, HTML5 and other web development frameworks. But as a programmer I love collect code snippets for my ease and store them on the cloud so I can get the access when I am in need and want to save my time while I am writing code. Out of the box I have a list of few image manipulation plugins which seems pretty impressive to me. Let's take a look:

1. Image Carousels

For simple image carousels you can use rcarousel. The plugin is good if you are planning to implement a simple image carousel. If you are looking for some CSS3 taste then take a look at slideshow using jmpress. The transitions effects are awesome.

2. Adipoli jQuery Image Hover Plugin

This is the best image hover plugin I used and available on the web so far. The plugin has to offer you some amazing effects. My favorite is the greyscale and popout, both effects are good if you plan to have a web based gallery.

3. Captify

If you are looking to have a caption for your images, then do that in style. Captify is a plugin let you have pretty image captions for the image. You can have the caption on the image by default or you can show it to the user on mouseover. You can take a look at a little demo here and download it from the GitHub

4. Spritely.net

Want to work with sprites but don't know how to kick off? Don't wait and go to Spritely. Before you download check the gallery examples. In short Spritely allows you to turn your images into a movie. Simply awesome!!

5. jParallax

I will be surprised if you have not heard about this plugin. One of the most amazing and powerful plugin or I should say a library that can make your images speak or work on their own. I am not going to describe what it does, so you have to go and look for yourself. Visit the demo page.

 No Rating

BingMap.JS - Jquery Plugin For Bing Maps

10. March 2012 16:39

API Jquery Microsoft  Projects  0 Comments

Bing maps are out there for a long time now and is getting mature pretty fast. I have used Bing maps myself in few of my projects and I remember as a first time user I have a hard time configuring it according to my project requirement. To get myself out of the overhead I searched the web for a jquery plugin, but I can't find a single jquery plugin for Bing Maps instead I found few for Google Maps. I do have some knowledge of jquery and Bing map API, so I decided to write a jquery plugin for Bing map in my free time that will handle all necessary configurations and all the hard work for me and more importantly save my time.

How I get started and how it ended up

Initially I started writing a plugin to just set up the default configuration like setting the map with different modes, zoom level and other necessary configurations, but I ended up doing something more. Besides just the normal configurations of the map I was also able to incorporate Bing map API to search and pinpoint the address on the map. Now if you have an address and you want that to be located on the map then you just have to write in the address in the address parameter and do the other necessary configuration like if you want to show the pushpin on the map or not, or you can set the description on the balloon tip when the user hover the mouse on the pushpin. You can also change the view modes and can also set the zoom level. Plenty of stuff in the plugin and I will add more to make it more flexible and more productive. The API thing in the plugin was just the test from my side, I never thought of using the API in the plugin when I started writing it. But I am happy that I ended up making something useful for myself and I am sure enough that it will help other fellow developers out there also.

Where to get the plugin?

I have a dedicated a page for the Bing Map plugin here. There are still few changes to be made on the page so that it can have more information. In the next phase I am planning to have a demo page and provide more information on plugin.

Make sure to read about the plugin and the configurations before you get started with the plugin at Bing map plugin home page.

If you are using NuGet then you can fire up the below command to install it into the Scripts folder.

If you have doubts and have suggestions for the plugin then please do drop me a comment or e-mail.

 No Rating

«1234»

Visit blogadda.com to discover Indian blogs Computers Blogs