Wednesday, 29 June 2016

Save files on disk using JavaScript or JQuery!

ou can save any file, or DataURL, or Blob on disk using HTML5's newly introduced "download" attribute.

Use cases:

1. Force browser to download/save files like PDF/HTML/PHP/ASPX/JS/CSS/etc. on disk
2. Concatenate all transmitted blobs and save them as file on disk - it is useful in file sharing applications

Microsoft Edge? (msSaveBlob/msSaveOrOpenBlob)

/**
 * @param {Blob} file - File or Blob object. This parameter is required.
 * @param {string} fileName - Optional file name e.g. "image.png"
 */
function invokeSaveAsDialog(file, fileName) {
    if (!file) {
        throw 'Blob object is required.';
    }

    if (!file.type) {
        file.type = 'video/webm';
    }

    var fileExtension = file.type.split('/')[1];

    if (fileName && fileName.indexOf('.') !== -1) {
        var splitted = fileName.split('.');
        fileName = splitted[0];
        fileExtension = splitted[1];
    }

    var fileFullName = (fileName || (Math.round(Math.random() * 9999999999) 
          + 888888888)) + '.' + fileExtension;

    if (typeof navigator.msSaveOrOpenBlob !== 'undefined') {
        return navigator.msSaveOrOpenBlob(file, fileFullName);
    } else if (typeof navigator.msSaveBlob !== 'undefined') {
        return navigator.msSaveBlob(file, fileFullName);
    }

    var hyperlink = document.createElement('a');
    hyperlink.href = URL.createObjectURL(file);
    hyperlink.target = '_blank';
    hyperlink.download = fileFullName;

    if (!!navigator.mozGetUserMedia) {
        hyperlink.onclick = function() {
            (document.body || document.documentElement).removeChild(hyperlink);
        };
        (document.body || document.documentElement).appendChild(hyperlink);
    }

    var evt = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true
    });

    hyperlink.dispatchEvent(evt);

    if (!navigator.mozGetUserMedia) {
        URL.revokeObjectURL(hyperlink.href);
    }
}

Here is how to use above function:


var textFile = new Blob(['Hello Sir'], {
   type: 'text/plain'
});
invokeSaveAsDialog(textFile, 'TextFile.txt');

You can pass two arguments over "SaveToDisk" function:

1. file-URL or blob or data-URL - it is mandatory
2. file name - it is optional

Here is "SaveToDisk" function uses new syntax of "createEvent" API:

function SaveToDisk(fileURL, fileName) {
        var save = document.createElement('a');
        save.href = fileURL;
        save.target = '_blank';
        save.download = fileName || 'unknown';

        var event = document.createEvent('Event');
        event.initEvent('click', true, true);
        save.dispatchEvent(event);
        (window.URL || window.webkitURL).revokeObjectURL(save.href);
}

Here is "SaveToDisk" function uses old syntax of "createEvent" API:

function SaveToDisk(fileURL, fileName) {
        var save = document.createElement('a');
        save.href = fileURL;
        save.target = '_blank';
        save.download = fileName || fileURL;
        var evt = document.createEvent('MouseEvents');
        evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0,
            false, false, false, false, 0, null);
        save.dispatchEvent(evt);
        (window.URL || window.webkitURL).revokeObjectURL(save.href);
}

Using "SaveToDisk" function

Force an image to be saved on disk instead of rendered by the browser:

SaveToDisk('imageURL.PNG', 'image.png');

Force downloading of pdf files (it will NEVER allow any browser specific pdf-reader to render/open your pdf files):

SaveToDisk('pdfURL.pdf');

Even you can enforce following web-browser specific files to be downloaded/saved on the disk instead of rendered within the browser!

JavaScript SaveToDisk('/javascript-file.js')
HTML SaveToDisk('/html-file.html')
CSS SaveToDisk('/css-file.css')
ASPX SaveToDisk('/aspx-file.aspx')
PHP SaveToDisk('/php-file.php')
MVC SaveToDisk('/controller/action-method')

Following apps are using "SaveToDisk" function to save files/blobs/etc. on disk:

DataChannel.js A library for realtime data/file sharing using WebRTC!
RTCMultiConnection.js A library for realtime audio/video/screen/data and file sharing using WebRTC!
Group File Sharing Sharing files over multiple peer connections concurrently
RecordRTC A library for WebRTC-Developers to record audio and video streams

Specification

1. https://developer.mozilla.org/en-US/docs/DOM/document.createEvent
2. http://www.w3.org/TR/DOM-Level-3-Events/#events-Events-DocumentEvent-createEvent

function SaveToDisk(fileUrl, fileName) {
    var hyperlink = document.createElement('a');
    hyperlink.href = fileUrl;
    hyperlink.target = '_blank';
    hyperlink.download = fileName || fileUrl;

    var mouseEvent = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true
    });

    hyperlink.dispatchEvent(mouseEvent);
    (window.URL || window.webkitURL).revokeObjectURL(hyperlink.href);
}

Tuesday, 9 February 2016

C Program to Sort the N Names in an Alphabetical Order

This C Program sorts the names in an alphabetical order. The program accepts names & then sorts the names in an alphabetical order using string operation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* C program to read N names, store them in the form of an array
* and sort them in alphabetical order. Output the given names and
* the sorted names in two columns side by side.
*/
#include <stdio.h>
#include <string.h>     

void main()
    {
    char name[10][8], tname[10][8], temp[8];
    int i, j, n;
    printf("Enter the value of n \n");
    scanf("%d", &n);
    printf("Enter %d names: \n", n);
    for (i = 0; i < n; i++)
        {
        scanf("%s", name[i]);
        strcpy(tname[i], name[i]);
        }
    for (i = 0; i < n - 1 ; i++)
        {
        for (j = i + 1; j < n; j++)
            {
            if (strcmp(name[i], name[j]) > 0)
                {
                strcpy(temp, name[i]);
                strcpy(name[i], name[j]);
                strcpy(name[j], temp);
                }
            }
        }
    printf("\n----------------------------------------\n");
    printf("Input \t NamestSorted names\n");
    printf("------------------------------------------\n");
    for (i = 0; i < n; i++)
        {
        printf("%s\t\t%s\n", tname[i], name[i]);
        }
    printf("------------------------------------------\n");
    }