Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Flow.js: Performing Uploads in Javascript

In this article we will discuss Flow.js, a JavaScript library which provides multiple, stable and resumable uploads.

Flow.js is a JavaScript library for angular.js framework that provides multiple, stable and resumable uploads using HTML5 file API and no third party JS dependencies required. The main purpose of Flow.js is uploading large files through HTTP. It allows users to upload files with pause/resume functionality. This even allows recovering uploads without losing state because only the files which are getting uploaded currently will be aborted and not the entire upload.

Flow.js has only HTML5 File API dependency. It splits the file into small chunks. It is supported by Mozilla Firefox 4+, Google Chrome 11+, Safari 6+ and Internet Explorer 10+.

Features

  • It provides multiple, stable and pause/resume uploads.
  • It recovers uploads without losing the state.
  • It provides drag and drop functionality with folder reader.
  • It handles errors.
  • It allows uploading folder.
  • It provides facility to preview the uploaded images.
  • It validates file and display the upload progress.

To use Flow.js, we should make use of the following CDN’s in your code:

Listing 1: CDN’s used in the code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="your path/resumable.js"></script>
<script src="your path/flow.js"></script>
<script src="your path/flow.min.js"></script>

These CDN’s should be included in the tag as shown in the below example.

Listing 2: Creating a simple example of an uploading file using flow.js

<!DOCTYPE html>
<html>
   <head>
      <title>Simple FlowJS Example</title>
      <meta charset="utf-8" />
      <link rel="stylesheet" type="text/css" href="style.css" />
      //To use Flow.js, use the following CDN’s
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
      <script src="resumable.js"></script>
      <script src="flowjs/flow.js"></script>
      <script src="flowjs/flow.min.js"></script>
   </head>
   <body>
      <div id="frame">
         //When you run the code, the below line will get display on the browser 
         <h1>This is simple example of uploading file</h1>
         //If there is an error while uploading; it will display this error message  
         <div class="resumable-error">
            Sorry, your browser is not supporting.
         </div>
         //The below classes are used when doing drag and drop functionality
         <div class="resumable-drop" ondragenter="jQuery(this).addClass('resumable-dragover');" ondragend="jQuery(this).removeClass('resumable-dragover');" ondrop="jQuery(this).removeClass('resumable-dragover');">
            Drop the files here to upload or <a class="resumable-browse"><u>select from your computer</u></a>
         </div>
         <div class="resumable-progress">
            <table>
               <tr>
                  <td width="100%">
                     <div class="progress-container">
                        //Display the progress bar while uploading file 
                        <div class="progress-bar"></div>
                     </div>
                  </td>
                  <td class="progress-text" nowrap="nowrap"></td>
                  <td class="progress-pause" nowrap="nowrap">
                     //Display the resume and pause images when you click on resume and pause links respectively
                     <a href="#" onclick="r.upload(); return(false);" class="progress-resume-link"><img src="resume.png" title="Resume upload" /></a>
                     <a href="#" onclick="r.pause(); return(false);" class="progress-pause-link"><img src="pause.png" title="Pause upload" /></a>
                  </td>
               </tr>
            </table>
         </div>
         <ul class="resumable-list"></ul>
         <script>
            var r = new Resumable({});
            // If Resumable.js is not supported, then move it on a different method
            if(!r.support) {
              $('.resumable-error').show();  //It will show error message
            } else {
              // Show a place for dropping/selecting files
              $('.resumable-drop').show();
              r.assignDrop($('.resumable-drop')[0]);
              r.assignBrowse($('.resumable-browse')[0]);
            
              // It handles the file add event function
              r.on('fileAdded', function(file){
                  // It show the progress bar
                  $('.resumable-progress, .resumable-list').show();
                  // Here, it shows resume, hide pause
                  $('.resumable-progress .progress-resume-link').hide();
                  $('.resumable-progress .progress-pause-link').show();
                  // Here, it adds the uploaded file to the list
                  $('.resumable-list').append('<li class="resumable-file-'+file.uniqueIdentifier+'">Uploading <span class="resumable-file-name"></span> <span class="resumable-file-progress"></span>');
                  $('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-name').html(file.fileName);
                  // Here, it starts start the uploading of file
                  r.upload();
                });
              r.on('pause', function(){
                  $('.resumable-progress .progress-resume-link').show();
                  $('.resumable-progress .progress-pause-link').hide();
                });
              r.on('complete', function(){
                  // Hide pause/resume when the upload has completed
                  $('.resumable-progress .progress-resume-link, .resumable-progress .progress-pause-link').hide();
                });
              r.on('fileSuccess', function(file,message){
                  // Reflect the file when upload has completed successfully
                  $('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html('(completed)');
                });
              r.on('fileError', function(file, message){
                  // Reflect the file when file has error in uploading
                  $('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html('(file could not be uploaded: '+message+')');
                });
              r.on('fileProgress', function(file){
                  // Defines the progress after completion of file upload
                  $('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html(Math.floor(file.progress()*100) + '%');
                  $('.progress-bar').css({width:Math.floor(r.progress()*100) + '%'});  //The ‘Math.floor()’ rounds a number downward to its nearest integer while showing progress bar
                });
            }
         </script>
      </div>
   </body>
</html>
                      

Details of code

  • The above program shows how to upload a file or drag and drop a file from your computer.
  • The class “resumable-drop” defined within div tag which contains ondragenter event that executes a JavaScript functionwhen a draggable element enters a drop target using addClass method that adds classes to each element in the set of matched elements.
  • The ondragend event triggers when the user finishes dragging an element and uses removeClass which removes one or more class names from the selected elements and ondrop event executes when a draggable element is dropped and uses the removeClass method.
  • The div class “resumable-progress” resumes and pauses links for uploading a file. The links can be provided for this using onclick event when a user clicks on the link.
  • Moving to script part, we are creating object of Resumable as r using new keyword. First, if Resumable is not supported, then object r falls back on a different method or else show the place for drag and drop of files or browse the files for uploading.
  • Next, it will show progress bar after adding files to the list. It also allows to resume or pause the uploading of file by using hide() and show() methods. It adds the file to the list using append () method that inserts content to the end of each element in the matched elements and displays the name of file using uniqueIdentifier which is numeric or alphanumeric string and upload the file using r.upload() method.
  • On pause () function, it shows resume or hide functionality and on complete () function, it hides resume and pause when upload has completed.· On success of upload, it displays the successful message with file name using file.uniqueIdentifier. If it finds any error while uploading, it displays the error message as ‘file could not be uploaded’ and it will show the progress bar while uploading and uses Math.floor () rounds a number downward to its nearest integer while showing progress bar.

When you run the above script, you would see the following output screen:

Figure 1. File Upload Example

Drag and drop the file or click on “select from your computer” link to upload your file. After uploading the file, you would get below screen:

Figure 2. File Upload Example (After uploading file)

Setting up Flow.js with server

The functionality of flow.js almostworks in user’s browser. Sometimes files of the flow.js reassembled from chunks of server side which can be some sort easy work and it can use any web framework for uploadingfiles.

To work with uploading files, there are some parameters used along with all requests as described below:

  • flowChunkNumber: It represents the number of chunk in the current upload. By default the first chunk is always 1.
  • flowTotalChunks: It defines the total numbers of chunks.
  • flowChunkSize: It defines the size of chunk. By using this value and flowTotalSize, you can calculate total number of chunks.
  • flowTotalSize: It represents total size of the file.
  • flowIdentifier: It is an unique identifier of the file in the request.
  • flowFileName: It is a name of the original file name.
  • flowRelativePath: It represents the relative path to upload a file from the directory.

Sometimes you need to upload the same chunk more than one time. So in that case, you need to make use of Flow.js on unstable network environment.

There are some HTTP status codes for every request in Flow.js.

  • 200, 201, 202 codes are used when chunk is correct and was accepted. There is no need to upload it again.
  • 404, 415, 500, 501 codes are used when there is an error while uploading or cancel of uploading process.
  • Anything else specifies when there is a wrong in uploading but tries re-uploading the file.

As you know, Flow.js extension is used for angular.js framework. You can use the above HTTP status codes as options for Flow.js as shown below:

var app = angular.module (‘app’, [‘flow’])
.config([‘myFlowFactory’, function ( myFlowFactory) {
    myFlowFactory.defaults={
    target: ‘/file directory’,
   permanentErrors: [404, 500, 501]
};
   myFlowFactory.on(‘catchAll’, function(event){
      // code here
   });
      // code here
}]);

The above codes are used when there is an error while uploading or cancel of uploading process.

Handling GET requests

You could resume the upload process even after restart of your browser by enabling the testChunks option. You can use post requests to receive data and get requests are used to extend the support using the same parameters. If request returns 200, 201, 202 HTTP status codes, then we could consider that the chunk has been completed. If it returns 404, 415, 500, 501 status codes, then we could assume that upload is cancelled or stopped. Lastly, if it returns anything else, we could say that something went wrong in uploading of a file.

Flow.js Configuration

In Flow.js, you could load the object of flow with some of the configuration options as mentioned below:

  • target : It is a target URL of the POST request which can be a string or function. If the target URL is a function, then it would pass a flow file, flow chunk and isTestBoolean. The default is /.
  • singleFile : This option is used for uploading single file. Consider you had uploaded one file, then if you want to upload second file, it will overtake the first file and first file will get canceled. By default it is false.
  • chunkSize : It defines size of the uploaded data chunk in bytes. The uploaded data chunk will be at least size and up to two the size.
  • forceChunkSize : This option forces all chunks should be less than or equal to chunkSize. Otherwise, it makes last chunk must be greater than or equal to chunkSize.
  • simultaneousUploads : It defines the number of simultaneous uploads. The default number of uploads is 3.
  • fileParameterName : It is the parameter name used for the file chunk. The default parameter is file.
  • query: It is an object or a function used to include extra parameters in the POST with data. If it is a function, then it would pass a flow file, flow chunk and isTestBoolean. The default is {}.
  • headers : It is an object or a function used to include extra headers in the POST with data. If it is a function, then it would pass a flow file, flow chunk and isTestBoolean. The default is {}.
  • withCredentials: By default, the CORS requests do not send or set cookies in the Flow.js. To send or set the cookies, you must set the withCredentials property to true. The default value will be false.
  • method : The methods such as multipart or octet are used to supply chunks to the server. The default method will be multipart.
  • testMethod : This method is used when chunks are being tested. If it is a function, then it would pass a flow file, flow chunk arguments. The default is GET.
  • uploadMethod : This method is used, when chunks are being uploaded. If it is a function, then it would pass a flow file, flow chunk arguments. The default is GET.
  • prioritizeFirstandLastChunk : It gives priority for first and last chunks of the files. It is useful only if file is valid for your service from only the first or last chunk. The default value is false.
  • testChunks : Uses GET requests to check whether chunks are exist or not in the Flow.js. It enables to resume your upload even after browser crash or restart of the computer if you are working on server side.
  • preprocess : It is an optional function used to process the chunk before testing and sending. It uses chunk as parameter and calls the preprocessFinished method on the chunk when completed.
  • generateUniqueIdentifier : It generates unique identifier for the each file in Flow.js.
  • maxChunkRetries : It defines the maximum number of retries for file upload before the upload is failed. It includes the possible values as any positive integers and undefined.
  • chunkRetryInterval : It represents interval time for a chunk to be retried on a non permanent error. It includes values such as any positive integer and undefined for immediate retry. The default value is undefined.
  • progressCallbacksInterval : It represents interval time between progress callbacks and can be set to 0 to handle each progress callback. The default time interval is 500.
  • speedSmoothingFactor : This option is used for specifying average upload speed. Set the number to 1, which makes average upload speed equal to current upload speed. If you want longer file uploads, then set the number to 0.02. So that there will be accurate in time remaining estimation and this option can be adjusted with progressCallbacksInterval parameter.
  • successStatuses : It defines the success message. The status codes 200, 201, 202 are used when chunk is correct and was accepted.
  • permanentErrors : It defines the error message if status codes 404, 415, 500, 501 are used when there is an error while uploading or cancel of uploading process.

Flow.js Properties

  • The Flow.js contains some of the properties as described below:
  • .support : It contains boolean value that determines whether the Flow.js is supported by the current browser or not.
  • .supportDirectory : It includes boolean value that indicates whether browser supports directory upload or not.
  • .opts : It represents object of the configuration of the Flow.js instance.
  • .files : It specifies an array of file objects added by the user.

Flow.js Methods

The Flow.js contains some of the methods as described below:

  • .assignBrowse(domNodes, isDirectory, singleFile, attributes) : This method assigns browse actions to one or more DOM nodes. This method includes four parameters as specified below:
    • domNodes : It represents the single node or array of nodes.
    • isDirectory : If this method is set to true, it allows directories to be selected. In chrome, it can be checked with supportDirectory property.
    • singleFile : If you don’t want to upload multiple files upload, then set this method to true.
    • attributes : It sets custom attributes on input fields by using object of keys and values.
  • .assignDrop(domNodes) : This method assigns DOM nodes as drop target.
  • .on(event, callback) : Attach an event handler function to the selected elements.
  • .off(event, callback)
    • .off() : It removes the all events.
    • .off(event) : It removes the callbacks of specific event.
    • .off(event, callback) : It removes the specific callback of event and callback is a function.
  • .upload() : It starts or resume the uploading of file.
  • .pause() : It pause the uploading of file.
  • .resume() : It resumes the uploading of file.
  • .cancel() : It removes the file or cancel the uploading of a file.
  • .progress() : It defines the current upload progress of the file ranging between 0 and 1.
  • .isUploading() : It determines that whether the instance is uploading anything or not.
  • .addFile() : It adds HTML5 file object to the list of files.
  • .removeFile() : It removes or cancels the upload of the file from the list.
  • .getFromUniqueIdentifier(UniqueIdentifier) : It is used to get object of the file from its Unique Identifier.
  • .getSize() : It determines the total size of the file in bytes.
  • .sizeUploaded() : It determines the total size of the uploaded files in bytes.
  • .timeRemaining() : It specifies the amount of remaining time to upload the files. The time remaining will be equal to infinity value if the speed is zero.

Flow.js Events

The Flow.js contains some of the events as described below:

  • .fileSuccess(file, message, chunk) : It specifies that file is successfully completed. It includes three parameters. The file parameter is a FlowFile instance, the message parameter contains response of the server and last parameter chunk is a FlowChunk instance. It is possible to access status of the response by using xhr object chunk.xhr.status.
  • .fileProgress(file, chunk) : This event shows the progress of the uploading file. There are two parameters. The file parameter is a FlowFile instance and second parameter chunk is a FlowChunk instance.
  • .fileAdded(file, event) : It is used to add file to upload list and file validation process. You can’t start file uploading process using the flow.upload() function. You can use only event object from when the file was added.
  • .fileAdded(array, event) : This event is same as above event, but can be used for multiple file validation process.
  • .fileSubmitted(array, event) : It is used to submit the files which are currently added files.
  • .fileRetry(file, chunk) : This event is used to retry the uploading of files which are failed to upload specified files.
  • .fileError(file, message, chunk) : It gives an error message when there is an error during upload of file.
  • .uploadStart() : It represents upload has been started for the specified file in flow object.
  • .complete() : It determines that process of uploading files completed.
  • .progress() : It determines that progress of uploading files.
  • .error(message, file, chunk) : It display the error which has occurred during file upload. The message parameter contains response of the server, the file parameter is a FlowFile instance and the last parameter chunk is a FlowChunk instance.
  • .catchAll(event, …) : This event represents all the above defined events with the same callback function.

The events can be caught inside the flow-init directive using div tag as specified below:

  < div flow-init 
     flow-file-success=” The file is successfully completed… “
     flow-file-progress=” The progress of the uploading file…“
     flow-file-added=” The file is added to the upload list…”
     flow-files-added=” The files are added to the upload list… ”
     flow-files-submitted=” Submit the currently added files…”
     flow-file-retry=” Retry the uploading of failed files…”
     flow-file-error=” Error message when there is an error during upload of file…”
     flow-error=” Error message when there is an error during upload of file…”   
     flow-complete=” The process of uploading files completed…”
     flow-upload-started=”The upload has been started for the specified file…”
     flow-progress=”It determines progress of uploading files…”
  //You can also define an event within the flow-init
  <div flow-file-progress=” The progress of the uploading file…“></div>
  </div>
  

You can even catch an event in a controller. You can catch events by using $on method, if the controller is defined within flow-init directive or in a child scope. The events can be prefixed with flow::.

  $scope.$on(‘flow::fileAdded’, function (event, $flow, flowFIle){
  event.preventDefault();   // This method stops the default action of an element from happening.
                          //It prevent file from uploading.
  }
  

Here, the function takes three parameters. One is event, which provides an event functionality when user adds files to the upload list. Second parameter is $flow is a flow instance and last parameter flowFile access the constructor of the FlowFile using Flow.FlowFile.

FlowFile

You can also access the constructor of the FlowFile by using Flow.FlowFile.

FlowFile Properties

Flow.FlowFile has some of the properties as described below:

  • flowObj : It represents reference to the parent Flow object.
  • .file : It defines the HTML5 file object.
  • .name : It specifies name of the file.
  • .relativePath: The relative links points to a file or file path. You can use relative links only when linking to pages or files within your site. If this relative path does not exist, then it defaults to the file name.
  • .size : It determines the size of the file in bytes.
  • .uniqueIdentifier : It generates unique identifier for the each file object in Flow.js. This unique identifier can be used as reference for server while uploading the file.
  • .averageSpeed : It specifies the average speed of the uploading files. The speed is bytes per second.
  • .currentSpeed : It specifies the current speed of the uploading files. The speed is bytes per second.
  • .chunks : It represents array of FlowChunk items during upload of files.
  • .paused : It specifies the files which are in paused state.
  • .error : It determines whether file has encountered an error while uploading process.

FlowFile Methods

Flow.File also includes some of the methods as described below:

  • .progress(relative) : It represents the current upload progress of the file which is indicated by the floating number 0 and 1. It has the parameter called relative and if it is set to true, the value will be relative to all the files in the Flow.js instance.
  • .pause() : It pause the uploading of file.
  • .resume() : It resumes the uploading of file.
  • .cancel() : It removes the file or cancel the uploading of a file from the list.
  • .retry(): This method is used to retry the uploading of files which are failed to upload specified files.
  • .bootstrap() : It re-constructs the state of the FlowFile object by using chunks which can be reassigned and XMLHttpRequest instances.
  • .isUploading() : It determines that whether the file chunk is uploading or not using boolean value.
  • .isComplete() : It determines that whether the file has completed the uploading process or not and received a server response.
  • .sizeUploaded() : It returns the size of the uploaded file in bytes.
  • .timeRemaining() : It specifies the amount of remaining time to upload the files in terms of seconds. It specifies the average speed of the uploading files. The time remaining will be equal to infinity value if the speed is zero.
  • .getExtension() : It returns the extension of the file in lower case.
  • .getType() : It returns the type of the file.

Assigning flow to parent scope

You could assign flow to a parent scope by using flow-name attribute and set it to any variable in the scope.

  <div flow-init flow-name=”myobj.flow”>
  //code here
  </div>
  

Here, flow is set to flow name called myobj.flow.

You can also initialize a flow object with an existing flow object by using the flow-object attribute and set it with existing flow object on scope.

  <div flow-init flow-object=”myExistingFlowObj”>
  //code here
  </div>
  

Here, flow is initialized with existing flow object myExistingFlowObj and no new flow object is created.

Conclusion

This article has given you a brief glimpse of Flow.js JavaScript library and its features. The article covered some basic properties, methods, events and configuration of Flow.js. I have tried to cover most of the aspects of Flow.js library. I hope you have enjoyed reading this article.

Links

Flow.js official website

https://github.com/flowjs/flow.js



I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login